mySQL将行从2个表移动到其他表

时间:2015-05-11 19:38:06

标签: mysql sql insert inner-join

你好,我似乎无法弄清楚为什么这个sql语句不起作用?

我正在尝试将table1和table2中的行移动到table3和table4中。我认为最简单的方法是选择具有内连接的行,然后进行2 INSERT INTO。

BEGIN;
INSERT INTO table3 (id, content, createdBy, createdDate, endTime, startTime) 
VALUES (table1.id, table1.content, table1.createdBy, table1.createdDate, table1.endTime, table1.startTime);
INSERT INTO table4 (table3_Id, sometableid) 
VALUES (table2.table3_Id, table2.sometableid);
SELECT table1.id, 
table1.content, 
table1.createdBy, 
table1.createdDate, 
table1.endTime, 
table1.startTime, 
table2.table2_id, 
table2.sometableid
FROM table1 
INNER JOIN table2 
ON table1.id = table2.table1_id
WHERE table1.endTime < NOW()
COMMIT;

当我运行这个sql时,它输出#1054 - 未知列&#39; table1.id&#39;在&#39;字段列表&#39;

如果有人有任何好的想法,或者可以指出我正确的方向,那将非常感激!

1 个答案:

答案 0 :(得分:0)

使用INSERT INTO ... SELECT

INSERT INTO table3 (id, content, createdBy, createdDate, endTime, startTime)
SELECT id, content, createdBy, createdDate, endTime, startTime
FROM table1
WHERE endTime < NOW();

INSERT INTO table4 (table3_Id, sometableid)
SELECT t2.table2_id, t2.sometableid
FROM table1 AS t1
JOIN table2 AS t2 ON t1.id = t2.table1_id
WHERE t1.endTime < NOW();