首页 > 解决方案 > 仅选择具有 COLUMN= 的行如果匹配存在,否则 COLUMN IS NULL

问题描述

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

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'我希望返回第三行。

标签: sqloraclepostgresql

解决方案


如果您正在寻找一排:

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);

推荐阅读