我正在试图弄清楚如何在表格中插入/更新行。
我有两个表,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
答案 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)