【问题标题】:sql update multiple rows, with condition in each row [closed]sql更新多行,每行都有条件[关闭]
【发布时间】:2018-12-27 13:28:41
【问题描述】:

我有一个包含 A、B、C 列的表格。

如果 A 和 B(A、B 一起是唯一的)我想更新 C 列,因此伪代码如下所示:

update table 
set (a = 1, b = 1, c = 1000)
    (a = 2, b = 2, c = 2000)
    (a = 3, b = 3, c = 3000)
where a and b matches columns

如何用 SQL 编写?

【问题讨论】:

  • 您在此处标记了 3 个不同的 RDBMS,并且语法可以/确实因 RDBMS 而异。我已删除所有 RDBMS 标签,但是,请修改您的问题并更新标签以包含 only真正 使用的 RDBMS。谢谢。
  • “如果 A 和 B 是唯一的,则更新 C 列”是什么意思?你的问题很混乱。如果要更新单个列,为什么要在update 中设置三个值?

标签: sql


【解决方案1】:

我认为你可以使用case 表达式:

update table 
    set c = (case when a = 1 and b = 1 then 1000
                  when a = 2 and b = 2 then 2000
                  when a = 3 and b = 3 then 3000
             end)
where (a = 1 and b = 1) or (a = 2 and b = 2) or (a = 3 and b = 3);

【讨论】:

  • @forpas 。 . .错字已修正。
【解决方案2】:

多个更新适用于任何 RDBMS

update yourtable set c = 1000 where a = 1 and b = 1
update yourtable set c = 2000 where a = 2 and b = 2
update yourtable set c = 3000 where a = 3 and b = 3

人们会认为 UPDATE 语句应该是相当标准的。
但是当从表或子查询更新时,语法可能会有所不同。

这适用于 MS Sql Server

update t
set c = q.c
from yourtable t
join (values 
   (1, 1, 1000)
  ,(2, 2, 2000)
  ,(3, 3, 3000)
) q(a, b, c)
on t.a = q.a and t.b = q.b

这适用于 Postgresql

update yourtable t
set c = q.c
from 
(values 
   (1, 1, 1000)
  ,(2, 2, 2000)
  ,(3, 3, 3000)
) q(a, b, c)
where q.a = t.a and q.b = t.b

这适用于 MySql

update yourtable t
join 
(
   select 1 as a, 1 as b, 1000 as c
   union all select 2, 2, 2000
   union all select 3, 3, 3000
) q on q.a = t.a and q.b = t.b
set t.c = q.c

这适用于 Oracle RDBMS

update yourtable t 
set t.c = 
(
   select q.c
   from 
   (
      select 1 as a, 1 as b, 1000 as c from dual
      union all select 2, 2, 2000 from dual
      union all select 3, 3, 3000 from dual
   ) q
   where q.a = t.a and q.b = t.b
)

【讨论】:

    【解决方案3】:

    如果你的意思是当a 等于b

    UPDATE t 
    SET c = 1000 * a
    WHERE a = b;
    

    适用于任何 rdbms。
    demo

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-08-24
      • 2019-05-24
      • 1970-01-01
      • 2018-07-18
      • 1970-01-01
      • 1970-01-01
      • 2023-03-07
      • 2021-09-12
      相关资源
      最近更新 更多