mysql – 将行从一个表移动到另一个表

如果我有两个在结构上相同的表,我怎样才能从一个表中移动一组到另一个表?

这组行将从select查询中确定。

例如:

customer table person_id | person_name | person_email 123 tom tom@example.com persons table person_id | person_name | person_email 

样本select将是:

 select * from customer_table where person_name = 'tom'; 

我想从客户表格移动到人员表格

理想情况下,从原始表中删除数据,但这不会是一个交易断路器。

一个简单的INSERT INTO SELECT语句:

 INSERT INTO persons_table select * from customer_table where person_name = 'tom'; 

 DELETE FROM customer_table where person_name = 'tom'; 
  INSERT INTO Persons_Table (person_id, person_name,person_email) SELECT person_id, customer_name, customer_email FROM customer_table WHERE "insert your where clause here"; DELETE FROM customer_table WHERE "repeat your where clause here"; 

法比奥的答案确实不错,但需要很长的执行时间(正如Trilarion已经写过的那样)

我有一个更快的执行其他解决scheme。

 START TRANSACTION; set @N := (now()); INSERT INTO table2 select * from table1 where ts < date_sub(@N,INTERVAL 32 DAY); DELETE FROM table1 WHERE ts < date_sub(@N,INTERVAL 32 DAY); COMMIT; 

@N在开始时获得时间戳,并用于这两个命令。 一切都在交易中,以确保没有人感到困扰

 INSERT INTO Persons_Table (person_id, person_name,person_email) SELECT person_id, customer_name, customer_email FROM customer_table ORDER BY `person_id` DESC LIMIT 0, 15 WHERE "insert your where clause here"; DELETE FROM customer_table WHERE "repeat your where clause here"; 

您还可以使用ORDER BY,LIMIT和ASC / DESC来限制和select要移动的特定列。

我必须解决同样的问题,这是我用作解决scheme。

要使用此解决scheme,源表和目标表必须完全相同,并且在第一个表中必须具有唯一的id和自动增量(以便相同的id不会被重用)。

可以说table1和table2有这个结构

 |id|field1|field2 

你可以做这两个查询:

 INSERT INTO table2 SELECT * FROM table1 WHERE DELETE FROM table1 WHERE table1.id in (SELECT table2.id FROM table2) 
 BEGIN; INSERT INTO persons_table select * from customer_table where person_name = 'tom'; DELETE FROM customer_table where person_name = 'tom'; COMMIT;