【问题标题】:How to update one table based on the data of an other table?如何根据另一张表的数据更新一张表?
【发布时间】:2021-01-06 10:47:01
【问题描述】:

我在 mySQL 中有以下 2 个表。如果table_1 中不存在该数据或数据已更改,我想用table_2 的数据更新table_1

这些是我的桌子:

table_1:

id    name    desc     price 
------------------------------
1     a       audi        100
2     b       bmw         221
3     c       mercedes    331 

table_2:

id    name    desc      price
------------------------------
1     a       audi         1200
2     b       bmw          250
3     c       mercedes     500
4     d       opel         400
5     e       volkswagen   340

我想要的输出是:

table_1

id    name    desc      price
------------------------------
1     a       audi         1200
2     b       bmw          250
3     c       mercedes     500
4     d       opel         400
5     e       volkswagen   340

这是我尝试过的:

UPDATE table_1
   SET (name, desc) = (SELECT table_2.name, table_2.desc
                         FROM table_2 t2
                        WHERE table_1.id = table_2.id)
 WHERE EXISTS (
    SELECT 1
      FROM table_2
     WHERE table_1.id = table_2.id )

这是我得到的:

Error Code: 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 '(name, desc) = (SELECT table_2.name, table_2.desc                          FROM ' at line 2    0.000 sec

**请注意,我的桌子实际上要大得多。 PS 我正在使用 Toad。

【问题讨论】:

  • 删除 table1 并重命名 table2 是一种选择,但我不喜欢这么快删除数据,担心这可能会影响整个过程。 table_1在不同的程序中使用,怕链接误入歧途。
  • @RiggsFolly 你刚刚删除了你的第一条评论吗?
  • 是的,我认为这可能被认为有点滑稽
  • 另一个问题可能是您可以保证哪一列在两个表上都是唯一的并且永远不会改变。所以你可以用我们来匹配 2 个表上的行
  • 嗯...这可以使用 sql 函数解决吗? column1s 是唯一的。身份证

标签: mysql sql sql-update toad sql-function


【解决方案1】:

使用 INSERT on DUPLICATE 机制可以在一个非常简洁的查询中完成此操作

INSERT INTO table_1 (`id`, `name`,`desc`,`price`)
    (
     SELECT `t2`.`id`, `t2`.`name`, `t2`.`desc`, `t2`.`price` 
     from table_2 t2 
     where id = t2.id
    )
ON DUPLICATE KEY UPDATE `name`=`t2`.`name`, 
                        `desc`=`t2`.`desc`, 
                        `price`=`t2`.`price`;

【讨论】:

  • 上面写着Error Code 1054 Unknown column id in field list。这怎么可能?我和你有相同的列名
  • @我在 MySQL Workbench 8.0 上试用
  • 对不起,我搞定了。我的表被命名为table_1table_2 而不是table1table2。谢谢你。我想我现在可以手动删除table_2 了?
  • 我的错,我应该坚持问题中使用的名称,对不起
  • 没问题。还有1个问题。你为什么用t2?它代表什么?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-11-16
  • 1970-01-01
相关资源
最近更新 更多