【问题标题】:UPDATE table SET with multi values具有多个值的更新表 SET
【发布时间】:2018-04-28 01:30:57
【问题描述】:

我在网上花了很多时间试图寻找答案但没有成功,所以我决定发布以下内容。 我有以下表格:

TABLE_1
+------------+---------------+
| child_id   | mother_id     |
+------------+---------------+
|          1 |             4 |
|          2 |             3 |
|          3 |             2 |
|          4 |             1 |
+------------+---------------+

TABLE_2
+------------+---------------+
| child_id   | mother_id     |
+------------+---------------+
|          1 |             0 |
|          2 |             0 |
|          3 |             0 |
|          4 |             0 |
+------------+---------------+

我想用表 1 中的 mother_id 值更新表 2 中的 mother_id 值。 当然上面的例子可以手动解决:

UPDATE table2 SET mother_id = 1 where child_id = 4;
UPDATE table2 SET mother_id = 2 where child_id = 3;
UPDATE table2 SET mother_id = 3 where child_id = 2;
UPDATE table2 SET mother_id = 4 where child_id = 1;

但是让我们假设我有数千行要更新。有没有什么办法可以使用选择连接查询(在 child_id 上)与更新混合,以便只有几行代码?

谢谢。

【问题讨论】:

  • 你想让 table2 匹配 table1?
  • 是的,我想使用表 1 中的值更新表 2。

标签: mysql join sql-update


【解决方案1】:

通过内连接有效地完成

update table_2 
inner join table_1 
on table_2.child_id = table_1.child_id
set table_2.mother_id = table_1.mother_id;

【讨论】:

    【解决方案2】:
    UPDATE
     table_2 AS t2 
     INNER JOIN table_1 AS t1 
       ON t2.child_id = t1.child_id
    SET t2.mother_id = t1.mother_id;
    

    您需要根据匹配的child_id 连接两个表,然后将mother_id 的值从table_1 设置为table_2 的值。

    这是其中的demo

    【讨论】:

    • 太棒了!有用。也感谢你的演示,它真的帮助我理解了 UPDATE 如何与 JOIN 一起工作。
    猜你喜欢
    • 2015-10-03
    • 1970-01-01
    • 1970-01-01
    • 2017-10-18
    • 2020-06-19
    • 2011-07-21
    • 2020-01-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多