如果存在匹配项,则仅选择COLUMN = <value>的行,否则选择COLUMN IS NULL

时间:2019-07-08 18:48:09

标签: sql oracle postgresql

下面是一个示例脚本来演示该问题:

CREATE TABLE person (
  id NUMERIC PRIMARY KEY,
  name VARCHAR(255) NOT NULL,
  city VARCHAR(255)
);

INSERT INTO person(id, name, city) VALUES(1, 'John', 'New York');
INSERT INTO person(id, name, city) VALUES(2, 'Mike', 'Boston');
INSERT INTO person(id, name, city) VALUES(3, 'Ralph', NULL);

对于city='Boston',我只想返回 第二行。对于city='Chicago',我希望返回第三行。

2 个答案:

答案 0 :(得分:2)

如果您要查找一行:

select p.*
from person p
where city is null or city = 'Boston'
order by (city = 'value') desc
fetch first 1 row only;

如果可以有多个匹配项,那么我建议:

select p.*
from person p
where p.city = 'Boston'
union all
select p.*
from person p
where p.city is null and
      not exists (select 1 from person p2 where p2.city = 'Boston');

或者,使用窗口功能:

select p.*
from (select p.*, count(*) filter (where p.city = 'Boston') as cnt
      from person p
     ) p
where (cnt > 0 and p.city = 'Boston') or
      (cnt = 0 and p.city is null);

答案 1 :(得分:1)

尝试使用子查询,如下所示

select * from person
where 
   city='chicago' or 
  ( city is null and 
    1!=( select count(*) from person where city='chicago'  )
  )

demo link

ID  NAME    CITY
3   Ralph   


select * from person
where 
   city='Boston' or 
  ( city is null and 
    1!=( select count(*) from person where city='Boston'  )
  )

使用波士顿的结果

    ID  NAME    CITY
    2   Mike    Boston

Demo using boston