1. 程式人生 > >MySql 復制記錄並插入到當前表中

MySql 復制記錄並插入到當前表中

測試數據 create desc war des varchar query har tps

示例Table

技術分享圖片

create table tb_demo(
  id int unsigned auto_increment primary key,
  title varchar(50) not null default '',
  contents text,
  add_time int unsigned default 0
);

插入測試數據

insert into tb_demo (title,contents,add_time) values 
('#1 title 001','CONTENT 001 ABCD 1111',unix_timestamp()),
('#2 title 002','CONTENT 002 ABCD 2222',unix_timestamp()),
('#3 title 003','CONTENT 003 ABCD 3333',unix_timestamp()),
('#4 title 004','CONTENT 004 ABCD 4444',unix_timestamp());

預覽:\
技術分享圖片

復制並插入

下面的語句實現了:

  • 避開主鍵
  • 避開其他重復索引(雖然 demo 中沒有,但實際環境可能會用到)
  • 使用隨機字符,並合並兩個字符串
  • 記錄數據錄入時間
mysql> insert into tb_demo (title,contents,add_time) select concat(id,'__',title),concat('COPY_',contents),unix_timestamp() from tb_demo order by id desc limit 3;

Query OK, 3 rows affected (0.07 sec)
Records: 3  Duplicates: 0  Warnings: 0

執行結果:
技術分享圖片

MySql 復制記錄並插入到當前表中