我正在努力学习SQL语句。
我希望在具有复合主键的表中更新除某些行之外的所有行。
这就是我现在所做的:
UPDATE Products SET Active = 0
_
UPDATE Products SET Active = 1
WHERE (Id_A = 1 AND Id_B = 1 AND Id_C = 1) OR
(Id_A = 1 AND Id_B = 2 AND Id_C = 1) OR
(Id_A = 5 AND Id_B = 8 AND Id_C = 3) OR
.
.
.
etc
这有效,但我不喜欢它。我希望能够一次性完成。
有没有办法在SQL中执行此操作?
答案 0 :(得分:7)
你的意思是:
UPDATE Products SET Active = CASE WHEN
(Id_A = 1 AND Id_B = 1 AND Id_C = 1) OR
(Id_A = 1 AND Id_B = 2 AND Id_C = 1) OR
(Id_A = 5 AND Id_B = 8 AND Id_C = 3) OR
.
.
.
THEN 1 ELSE 0 END
答案 1 :(得分:2)
在某些SQL产品中,您可以进一步简化CASE
中的语法,将多个AND
和OR
删除为简单的IN
:
UPDATE Products
SET Active = CASE WHEN
(Id_A, Id_B, Id_C) IN
( (1, 1, 5), (1, 2, 1), (5, 8, 3) ... )
THEN 1 ELSE 0
END ;
要考虑的另一件事是,如果表有很多行(如数百万或数十亿)并且只有一小部分设置为Active=1
,那么完成更新可能会更有效率2假设你有(Active)
的索引(或(Active=1)
上的部分索引),语句类似于你从一开始就有的语句:
UPDATE Products SET Active = 0 WHERE Active = 1 ;
UPDATE Products SET Active = 1 WHERE ... ;
答案 2 :(得分:1)
您可以在更新语句中使用案例表达式吗?
像
这样的东西UPDATE Products
set Active = CASE WHEN (Id_A = 1 AND Id_B = 1 AND Id_C = 1) THEN 1
WHEN (Id_A = 1 AND Id_B = 2 AND Id_C = 1) THEN 1
.
.
.
ELSE 0 END