从另一个表插入表,但如果已存在则更新

时间:2018-06-18 14:06:05

标签: mysql sql phpmyadmin insert

我正在试图弄清楚如何在表格中插入/更新行。

我有两个表,real_table和temp_table,temp_table包含我想要更新real_table的所有数据。但是,其中一些行不存在于real_table中。所以我想运行一个基本上插入行的命令(如果它已经存在),如果它确实存在,则使用新值更新它。

我想要更新的主要内容是value列。这是我到目前为止的尝试:

INSERT INTO `real_table`(value_id, entity_type_id, attribute_id, store_id, entity_id, value)
FROM temp_table
VALUES (value_id, entity_type_id, attribute_id, store_id, entity_id, value)
ON DUPLICATE UPDATE
value = temp_table.value

我收到了错误

#1064 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'FROM temp_table VALUES (value_id, entity_type_id, attribute_id, store_id, entit' at line 2

2 个答案:

答案 0 :(得分:1)

您需要更正insert using select

的语法
INSERT INTO `real_table`(value_id, entity_type_id, attribute_id, store_id, entity_id, value)
SELECT value_id, entity_type_id, attribute_id, store_id, entity_id, value
FROM temp_table
ON DUPLICATE KEY UPDATE value = temp_table.value

确保您已定义唯一索引,以便利用ON DUPLICATE KEY UPDATE

答案 1 :(得分:0)

试试这个:

INSERT INTO real_table (value_id, entity_type_id, attribute_id, store_id, entity_id, value) SELECT temp_table VALUES (value_id, entity_type_id, attribute_id, store_id, entity_id, value)