我正在尝试弄清楚如何在表中插入/更新行。
我有两个表,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
最佳答案
您需要更正 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
关于mysql - 从另一个表插入表,但如果已存在则更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50911313/