MySql 复制记录并插入到当前表中

Posted 风在山路吹

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了MySql 复制记录并插入到当前表中相关的知识,希望对你有一定的参考价值。

示例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 复制记录并插入到当前表中的主要内容,如果未能解决你的问题,请参考以下文章