如何将一行从一个表更新到另一个表?

时间:2011-08-23 10:26:20

标签: mysql sql insert conditional sql-update

我尝试将表的某些行更新为不同的表,现在我只是想知道如何从一个表到另一个表插入一行,如:

INSERT INTO dialecte_org_5.tb_data_iae (
    SELECT * FROM dialecte_org_88.tb_data_iae WHERE id_dialecte = 2413
);

什么可以是相同的声明,但更新? 如果存在行,有没有办法制作这样的东西 - > “更新”,如果不是“插入”

THX

1 个答案:

答案 0 :(得分:2)

对于插入,您通常要为insert语句和select(http://dev.mysql.com/doc/refman/5.5/en/insert.html)指定完整字段列表:

INSERT INTO dialecte_org_5.tb_data_iae (field1, field2, field3)
SELECT field1, field2, field3
FROM dialecte_org_88.tb_data_iae WHERE id_dialecte=2413;

更新声明更像是这样(http://dev.mysql.com/doc/refman/5.0/en/update.html):

UPDATE dialecte_org_5.tb_data_iae t1
INNER JOIN dialecte_org_88.tb_data_iae t2 ON t1.id = t2.id
SET t1.field1 = t2.field1, t1.field2 = t2.field2, t1.field3 = t2.field3
WHERE t2.id_dialecte=2413

您也可以使用REPLACE INTO,它同时执行这两项操作,但是特定于MySQL,不受其他RDBMS(http://dev.mysql.com/doc/refman/5.0/en/replace.html)支持:

REPLACE INTO dialecte_org_5.tb_data_iae t1
INNER JOIN dialecte_org_88.tb_data_iae t2 ON t1.id = t2.id
SET t1.field1 = t2.field1, t1.field2 = t2.field2, t1.field3 = t2.field3
WHERE t2.id_dialecte=2413