需要写MySQL个case语句

Need to write MySQL case statement

我需要写一个 MySQL 语句,但不确定如何使用 case 语句来写它。

我想这样写:

SELECT 
    * 
    FROM 
        table 
    WHERE:

        IF sign_off_1 IS NOT NULL AND sign_off_1 IS NOT EQUAL TO 'Director' 
        sign_off_1_status MUST BE EQUAL TO Complete

        IF sign_off_2 IS NOT NULL AND sign_off_2 IS NOT EQUAL TO 'Director' 
        sign_off_2_status MUST BE EQUAL TO Complete

        IF sign_off_3 is IS NOT NULL AND sign_off_3 IS NOT EQUAL TO 
        'Director' sign_off_3_status MUST BE EQUAL TO Complete

有人知道编写此查询的正确语法吗?

您需要使用ORAND 运算符来模拟where 子句中的if 条件。试试这个。

SELECT *
FROM   table
WHERE  ( sign_off_1 <> 'Director'
         AND sign_off_1_status = 'Complete' )
        OR ( sign_off_2 <> 'Director'
             AND sign_off_2_status = 'Complete' )
        OR ( sign_off_3 <> 'Director'
             AND sign_off_3_status = 'Complete' ) 
        OR ( sign_off <> 'Director' 
             AND status <> 'Complete')

更新: 我不完全确定你的评论。但这就是我的理解。

WHERE  (( sign_off_1 <> 'Director'
         AND sign_off_1_status = 'Complete' )
        OR ( sign_off_2 <> 'Director'
             AND sign_off_2_status = 'Complete' )
        OR ( sign_off_3 <> 'Director'
             AND sign_off_3_status = 'Complete' )) 
        AND ( sign_off <> 'Director' 
             AND status <> 'Complete')

不清楚你想要达到什么目的。行是否需要满足所有三个条件,还是只满足其中一个?无需使用 CASE 表达式即可实现任一结果。

如果要求是使用 CASE 表达式,并且您需要所有三个条件都为真,您可以这样做:

SELECT t.id
  FROM mytable t
 WHERE CASE 
         WHEN t.sign_off_1 <> 'Director' AND t.sign_off_1_status = 'Complete'
         THEN 1
         ELSE 0
       END
     + CASE 
         WHEN t.sign_off_2 <> 'Director' AND t.sign_off_2_status = 'Complete'
         THEN 1
         ELSE 0
       END
     + CASE 
         WHEN t.sign_off_3 <> 'Director' AND t.sign_off_3_status = 'Complete'
         THEN 1
         ELSE 0
       END
     = 3

如果您只需要其中一个条件为真,您可以将 = 3 替换为 > 0

请注意,与文字的不等式比较足以保证该列不为空。 (如果列为 NULL,不等式比较将为 return NULL,而不是 TRUE。)

同样,不使用 CASE 表达式也可以获得相同的结果。