sql更新多行,每行带有条件
我有一个a、B、C列的表格 如果A和B是唯一的,我想更新C列,因此伪代码如下所示:sql更新多行,每行带有条件,sql,Sql,我有一个a、B、C列的表格 如果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中编写此代码?在任何RDBMS中都可以使用多个更新 update yourtable set c = 1000 where a = 1 an
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中编写此代码?在任何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
)
我想你可以用一个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);
如果你的意思是当a等于b时:
对于任何rdbms。
请参见您在此处标记了3种不同的RDBMS,不同RDBMS的语法可能/确实有所不同。我已经删除了所有的RDBMS标签,但是,请修改您的问题并更新标签,以仅包括您真正使用的RDBMS。谢谢。如果A和B是唯一的,更新C列意味着什么?你的问题很令人困惑。如果要更新单个列,为什么要在更新中设置三个值?可能重复@forpas。打字错误已经纠正了。
UPDATE t
SET c = 1000 * a
WHERE a = b;