74

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

行集将由选择查询确定。

例如:

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

我想将行从客户表移动到人员表

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

4

7 回答 7

136

一个简单的INSERT INTO SELECT语句:

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

DELETE FROM customer_table WHERE person_name = 'tom';
于 2013-11-06T20:11:32.817 回答
39
    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";
于 2013-11-06T20:12:00.587 回答
32

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

于 2015-07-01T09:02:02.150 回答
6
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 来限制和选择要移动的特定列。

于 2015-07-29T04:13:05.933 回答
5
BEGIN;
INSERT INTO persons_table select * from customer_table where person_name = 'tom';
DELETE FROM customer_table where person_name = 'tom';
COMMIT;
于 2017-02-11T12:36:37.113 回答
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)
于 2014-06-17T13:51:40.467 回答
1

要通过使用 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;
于 2018-04-28T05:58:25.830 回答