Use case in where clause [duplicate]

时间秒杀一切 提交于 2019-12-25 11:56:15

问题


I am trying to add case statement to where condition in a query. My query looks like below-

select * from table_name
where
if(id==1) then col1 = 0
else           col1 is null

As shown in above query I want to add col1 = 0 in where condition if id-==0 else I want col1 is null in where condition. I tried

select * from table_name
where 
case id =1 then (col1 = 0)
else col1 is null
end

But the syntax is incorrect. Is there any way to do this?


回答1:


SELECT *
FROM table_name
WHERE isnull(id, '')= CASE(id)
               WHEN 1
               THEN 0
               ELSE ''
           END;



回答2:


I am not sure of your requirement but you can try if below satisfies you

select * from table_name
where 
isnull(col1,'') = case when id = 1 then   0
else '' end

Also try

select * from table_name
where 
( col1 = 0 and id = 1) OR ( col1 is null and id<>1 )



回答3:


I think you are looking for a case when solution. Which can be used as below to fill in a specific column. You do need to select the other columns as well when you do this though.

select 
case when id = 1 then 0 else null end as col1
from table_name



回答4:


I think this is what you're looking for:

select case when id = 1 then 0 else null end as col1, * from table_name


来源:https://stackoverflow.com/questions/46977510/use-case-in-where-clause

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!