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

时间:2013-11-06 20:07:13

标签: mysql

如果我有两个结构相同的表,我如何将一组行从一个表移动到另一个表?

行集将根据选择查询确定。

例如:

customer table

person_id | person_name | person_email
123         tom           tom@example.com


persons table

person_id | person_name  | person_email

样本选择将是:

select * from customer_table where person_name = 'tom';

我想将行从customer表移到person表

理想情况下从原始表中删除数据,但这不会成为交易破坏者。

7 个答案:

答案 0 :(得分:95)

一个简单的INSERT INTO SELECT声明:

INSERT INTO persons_table SELECT * FROM customer_table WHERE person_name = 'tom';

DELETE FROM customer_table WHERE person_name = 'tom';

答案 1 :(得分:34)

    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";

答案 2 :(得分:25)

Fabio的答案非常好,但需要很长的执行时间(正如Trilarion已经写过的那样)

我还有一个更快执行的解决方案。

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在开始时获取时间戳,并用于两个命令。 一切都在交易中以确保没有人感到不安

答案 3 :(得分:3)

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来限制和选择要移动的特定列。

答案 4 :(得分:2)

BEGIN;
INSERT INTO persons_table select * from customer_table where person_name = 'tom';
DELETE FROM customer_table where person_name = 'tom';
COMMIT;

答案 5 :(得分:1)

我必须解决同样的问题,这就是我用作解决方案的方法。

要使用此解决方案,源表和目标表必须相同,并且必须在第一个表中具有唯一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)

答案 6 :(得分:0)

通过选择WHERE查询

来移动和删除特定记录
BEGIN TRANSACTION;
Insert Into A SELECT * FROM B where URL="" AND email ="" AND Annual_Sales_Vol="" And OPENED_In="" AND emp_count=""  And contact_person= "" limit 0,2000;
delete from B where Id In (select Id from B where URL="" AND email ="" AND Annual_Sales_Vol="" And OPENED_In="" AND emp_count="" And contact_person= "" limit 0,2000);
commit;