首页 > 解决方案 > 使用基于 id 的新列值更新整个列

问题描述

使用 MySQL,我当前的表看起来像

表 A:

 id_u | date       | other | calculation
----------------------------------
    1 | 2019-09-09 | ""    | 1
    2 | 2019-09-09 | ""    | 1
    4 | 2019-09-09 | ""    | 2
    5 | 2019-09-09 | ""    | 4

我有一个返回的查询(SELECT)

询问:

 id_u | calculation
-------------------
    2 | 12
    4 | 16

更新后想要的结果:

 id_u | date       | other | calculation
----------------------------------
    1 | 2019-09-09 | ""    | 1
    2 | 2019-09-09 | ""    | 12
    4 | 2019-09-09 | ""    | 16
    5 | 2019-09-09 | ""    | 4

如何更新calculation每个 ids 的列?

标签: mysqlsqljoinsql-update

解决方案


MySQL中,您可以使用语句JOIN中的子句UPDATE来执行跨表更新:

update tableA a inner join (
  select id_u, calculation   
    from <some table[s][joins]>
) b on a.id_u = b.id_u 
   set a.calculation = b.calculation;

其中,在这种情况下,使用的是在查询子句derived table范围之后生成表的表达式。INNER JOIN


推荐阅读