如何将数据从一个表复制到同一数据库中的另一个表?

时间:2019-10-11 06:21:56

标签: mysql

在MySQL中,如何将数据从一个表复制到同一数据库表中的另一个表?

我知道insert into select,但是要花很多时间才能做到这一点,尤其是在实时数据库中,我们不能冒险。

有一些条件:
1. table1是源表,table1_archives是目标表。
2. table1_archives已经有数据,因此我们只能追加。

我的尝试:

time mysqldump --log-error=$logfile --complete-insert --insert-ignore 
--no-create-info --skip-triggers --user=$dbuser --host=$host $dbname table1  
--where="created < now()-interval 10 month" > $filename

但是它的名字是table1,所以我不能将其插入table1_archives。

任何指导将不胜感激。

谢谢。

2 个答案:

答案 0 :(得分:1)

“但是要花很多时间才能做到”

有一个小技巧可以避免这种情况,然后insert into会更快地工作:

Insert into table1 select * from table2

技巧:

step-1: drop all indices from table2
step-2: execute query
step-3: create indices again

答案 1 :(得分:1)

在输出文件中,您需要将表名table1更改为table1_archives。不幸的是mysqldump没有任何办法。您将必须使用sed快速执行此操作,这会将输出文件中的所有内容从table1重命名为table1_archives

由于您的列还可以包含table1之类的内容,因此最好将其括在反引号中进行搜索和替换。

您还可以使用gzip压缩输出文件。

这是对我有用的命令

mysqldump -u USER -h  HOST -p --skip-add-drop-table --no-create-info --skip-triggers --compact DB table1 |\
  sed -e 's/`table1`/`table1_archives`/' | gzip >   filename.sql.gz