【发布时间】:2021-04-03 01:29:41
【问题描述】:
PostgreSQL 版本 11.6。 如果表中存在列值,则要求是选择/返回行,否则返回默认值。 列值作为输入传递给查询。 这是测试数据
create table test (id int,c1 varchar(10));
insert into test values (1,'A');
insert into test values (1,'B');
insert into test values (1,'C');
insert into test values (1,'D');
insert into test values (1,'E');
insert into test values (2,'F');
insert into test values (2,'G');
insert into test values (2,'H');
insert into test values (0,'Default');
我尝试了什么?
select * from test where id = coalesce((select distinct id from test where id = 1),0);
它将返回表中的所有id = 1 行。
select * from test where id = coalesce((select distinct id from test where id = 11),0);
它将返回表中的id = 0 默认行,因为id = 11 不在表中。
有没有更好的方法来做到这一点?因为我两次查询表以获得结果,它可能会降低性能。有什么有效的方法吗?
【问题讨论】:
标签: postgresql