如果我有两个结构相同的表,我如何将一组行从一个表移动到另一个表?
将从选择查询确定行集.
例如:
customer table
person_id | person_name | person_email
123 tom tom@example.com
persons table
person_id | person_name | person_email
Run Code Online (Sandbox Code Playgroud)
样本选择将是:
select * from customer_table where person_name = 'tom';
Run Code Online (Sandbox Code Playgroud)
我想将行从customer表移到person表
理想情况下从原始表中删除数据,但这不是一个交易破坏者.
Nel*_*son 105
一个简单的INSERT INTO SELECT语句:
INSERT INTO persons_table SELECT * FROM customer_table WHERE person_name = 'tom';
Run Code Online (Sandbox Code Playgroud)
DELETE FROM customer_table WHERE person_name = 'tom';
Run Code Online (Sandbox Code Playgroud)
Cod*_*key 35
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";
Run Code Online (Sandbox Code Playgroud)
小智 28
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;
Run Code Online (Sandbox Code Playgroud)
@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";
Run Code Online (Sandbox Code Playgroud)
您还可以使用 ORDER BY、LIMIT 和 ASC/DESC 来限制和选择要移动的特定列。
BEGIN;
INSERT INTO persons_table select * from customer_table where person_name = 'tom';
DELETE FROM customer_table where person_name = 'tom';
COMMIT;
Run Code Online (Sandbox Code Playgroud)