我需要编写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
有没有人知道编写此查询的正确语法?
答案 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)
您需要使用OR
和AND
运算符来模拟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')