4

我正在为一条 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 中做到这一点?

4

3 回答 3

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
于 2012-08-30T13:18:16.897 回答
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 ... ;
于 2012-08-30T13:26:23.463 回答
1

您可以在更新语句中使用 case 表达式吗?

就像是

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
于 2012-08-30T13:21:31.297 回答