在下面的查询中,我想在CASE的WHEN中添加一个AND条件,然后才可能吗?
例如WHEN'r'和table1.name =“jones”那么'非常高'
SELECT table1.id, table1.name,
CASE table1.event
WHEN 'r' THEN 'very high'
WHEN 't' THEN 'very low'
ELSE (SELECT table2.risk FROM table2 WHERE table2.value <= table1.value
ORDER BY table2.value DESC LIMIT 1)
END AS risk
FROM table1
ORDER BY FIELD( table1.event, 'r', 'f', 't' ), table1.value DESC
答案 0 :(得分:28)
您可以像这样重写您的语句以实现您想要的目标
SELECT table1.id, table1.name,
CASE
WHEN table1.event = 'r' AND table1.name = 'jones' THEN 'very high'
WHEN table1.event = 't' AND table1.name = 'smith' THEN 'very low'
ELSE (SELECT table2.risk FROM table2 WHERE table2.value <= table1.value
ORDER BY table2.value DESC LIMIT 1)
END AS risk
FROM table1
ORDER BY FIELD( table1.event, 'r', 'f', 't' ), table1.value DESC
请注意,您需要在table1.event
语句后删除CASE
。
documentation here
答案 1 :(得分:5)
任何评估为布尔值(true或false)的内容都可以在WHEN
语句的CASE
条件下。因此,您可以将'r'
替换为:
('r' AND table1.name='jones')
考虑到这一点,您可能不得不在table1.event
CASE
SELECT table1.id, table1.name,
CASE
WHEN (table1.event = 'r' AND table1.name='Jones') THEN 'very high'
WHEN table1.event = 't' THEN 'very low'
ELSE (SELECT table2.risk
FROM table2
WHERE table2.value <= table1.value
ORDER BY table2.value DESC LIMIT 1)
END AS risk
FROM table1
ORDER BY FIELD( table1.event, 'r', 'f', 't' ), table1.value DESC
答案 2 :(得分:3)
从case <column> when <value> then ...
切换到case when <condition> then ...
:
CASE
WHEN table1.event = 'r' AND table1.active = 1 THEN 'very high'
...