如果值存在,则SQL查询采取条件

时间:2014-11-17 10:00:40

标签: sql sqlite

我需要sql查询才能在值存在时应用条件。 例如。考虑表人

sl     Name          city        state
--------------------------------------
1      xxxxxxxx      chennai     TN
2      yyyyyyyy      coimbatore  TN
3      zzzzzzzz      cochin      KL

考虑以下查询

select * from person where state = "AD" and city = "visag"

将返回0行

我想要一个查询来应用' state =" AD"和城市=" visag"'只有当州=" AD"存在。

有没有办法在单个选择查询中执行此操作?

2 个答案:

答案 0 :(得分:1)

'AD'是否存在是另一个条件:

select * 
from person 
where (state = 'AD' and city = 'visag')
or not exists
(
  select * 
  from person
  where state = 'AD'
);

答案 1 :(得分:0)

select * from person 
where state = "AD" and city = "visag"
or (select count(*) from person where state = "AD") = 0