首页 > 解决方案 > 从另一个表插入表,但如果已经存在则更新

问题描述

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

我有两个表,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

标签: mysqlsqlphpmyadmininsert

解决方案


您需要使用 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


推荐阅读