【问题标题】:Insert into table from another table but update if already exist从另一个表插入表,但如果已经存在则更新
【发布时间】:2018-06-18 14:06:05
【问题描述】:

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

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

【问题讨论】:

    标签: mysql sql phpmyadmin insert


    【解决方案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

    【讨论】:

    • 它似乎已正确更新,但并未将任何新行插入到 real_table 中。
    • @user2963379 这是因为唯一属性,就像唯一列没有新值,这就是它每次更新的原因,如果您可以为表和表定义也有助于确定原因
    【解决方案2】:

    试试这个:

    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)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-09-21
      • 1970-01-01
      • 2021-06-03
      • 2020-05-09
      • 1970-01-01
      • 2018-12-17
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多