首页 > 解决方案 > 当所有表都没有主键时使用“SET”更新多列

问题描述

我有两个表如下。

表 A:

    ResultID     | ImportDate | Comment1
    ----------------------------------------------
    101          | 25-09-2019 | One in Table A
    ----------------------------------------------
    101          | 25-09-2019 | One copy in Table A
    -----------------------------------------------
    102          | 25-09-2019 | Two in Table A
    -----------------------------------------------
    103          | 25-09-2019 | Three in Table A
    -----------------------------------------------

表 B:

    ResultID     | ImportDate | Comment2
    ------------------------------------------
    101          | 26-09-2019 | One in Table B
    ------------------------------------------
    101          | 26-09-2019 | One copy in Table B
    ------------------------------------------
    104          | 26-09-2019 | four in Table B
    -------------------------------------------

所以输出应该看起来像

表 A:

ResultID     | ImportDate | Comment1
---------------------------------------------
101          | 26-09-2019 | One in Table B
---------------------------------------------
101          | 26-09-2019 | One copy in Table B
--------------------------------------------
102          | 25-09-2019 | Two in Table A
--------------------------------------------
103          | 25-09-2019 | Three in Table A
---------------------------------------------
104          | 26-09-2019 | four in Table B
    -------------------------------------------

问题:ResultID如果表 A 和表 B 之间匹配,我想得到 上面提到的结果表 A ,我想从表 B 中更新表 A 中的所有列ResultID。如果ResultID表 B 中的表 A 中不存在,则将其插入表 A。

注意: ResultId不是两个表中的主键。

我在 MySQL 中尝试过的内容: 如果ResultId是主键,则以下解决方案有效,但我想在ResultID不是主键时找到解决方案。

INSERT INTO TableA (ResultID, ImportDate, Comment1)
SELECT ResultID, ImportDate, Comment2 FROM TableB
ON DUPLICATE KEY UPDATE
  ImportDate = VALUES(ImportDate),
  Comment1 = VALUES(Comment1);

对于我的真实场景 - 我有 40 列和 50,000 行。

你能给我任何提示或解决方案吗?谢谢你。

标签: mysqlsqldatabase

解决方案


你可以这样表演。

SELECT CONCAT( "INSERT INTO ..... " )
FROM ....

如果这些表中不存在记录,则解析您的方式以生成 SQL 查询:) 快速而肮脏。


推荐阅读