SQL Case表达式使用问题:WHERE条件中添加EXCL过滤规则语法排查
你写的CASE表达式语法和逻辑都有问题,不属于放错位置的问题,是写法不符合SQL规则。
存在的问题
- 语法错误:WHERE子句的多个过滤条件需要用逻辑运算符(AND/OR)连接,你直接把CASE表达式写在
a.client = $client后面没有加AND连接符,属于语法结构错误,所以SQL无法运行。 - 逻辑错误:你要求「仅当$lab取EXCL时返回数据」,但你写的CASE逻辑是
$lab != 'EXCL'时返回1、等于时返回0,和需求完全相反。
正确写法
写法1:保留CASE表达式(适合后续有复杂分支扩展的场景)
select distinct c.value_1 from aprposcode a inner join aprwagerule b on a.client = b.client and a.wage_rule = b.wage_rule and b.scale_from != 'AAA-00' inner join aprvalues c on b.client = c.client and b.scale_from = c.dim_value and getdate () between c.date_from and c.date_to where a.post_code = $posc and a.client = $client and case when $lab = 'EXCL' then 1 else 0 end = 1
写法2:简化写法(无复杂逻辑时优先使用,可读性和性能更好)
不需要用CASE表达式,直接加等值判断即可:
select distinct c.value_1 from aprposcode a inner join aprwagerule b on a.client = b.client and a.wage_rule = b.wage_rule and b.scale_from != 'AAA-00' inner join aprvalues c on b.client = c.client and b.scale_from = c.dim_value and getdate () between c.date_from and c.date_to where a.post_code = $posc and a.client = $client and $lab = 'EXCL'
如果你的实际需求是「当$lab为EXCL时才追加业务字段过滤,否则忽略该过滤条件」,可以调整判断逻辑为and ($lab != 'EXCL' or 你的业务过滤条件),但按照你描述的需求,上述两种写法已经可以满足要求。
内容的提问来源于stack exchange,提问作者Fozzy
相关产品推荐
相关产品推荐

