您的当前位置:首页正文

MySQL在where后面使用case when

2024-11-11 来源:个人技术集锦

在MySQL中,在where后面使用case when的说明

报错语句

select * 
from A, B
where B.name in
CASE
    when A.id = 0 then ('aaa', 'bbb')
    when A.id = 1 then ('bbb', 'ccc')
    when A.id = 2 then ('ccc', 'ddd')
END

正确写法:将B.name in 放到CASE END 中

select * 
from A, B
where 
CASE
    when A.id = 0 then B.name in ('aaa', 'bbb')
    when A.id = 1 then B.name in ('bbb', 'ccc')
    when A.id = 2 then B.name in ('ccc', 'ddd')
END

补充:当使用 B.name = 时,将不会出现以上问题,也就是如下写法也正确

select * 
from A, B
where B.name = 
CASE
    when A.id = 0 then 'aaa'
    when A.id = 1 then 'bbb'
    when A.id = 2 then 'ccc'
END
Top