需要编写MySQL case语句

时间:2015-02-14 16:40:13

标签: mysql sql case

我需要编写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

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

2 个答案:

答案 0 :(得分:2)

目前尚不清楚您想要实现的目标。一行是否需要满足所有三个条件,或只需要其中一个条件?无需使用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,则不等式比较将返回NULL,而不是TRUE。)

同样,可以在不使用CASE表达式的情况下实现相同的结果。

答案 1 :(得分:0)

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

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')