Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/postgresql/10.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
PostgreSQL验证表值并返回else返回默认值_Postgresql - Fatal编程技术网

PostgreSQL验证表值并返回else返回默认值

PostgreSQL验证表值并返回else返回默认值,postgresql,Postgresql,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 i

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
不在表中

select * from test where id = coalesce((select distinct id from test where id = 11),0);

有没有更好的办法?因为我查询了两次表以获得结果,这可能会降低性能。有什么有效的方法可以做到这一点吗?

嗯,我不认为你的方法有一半不好。。。这取决于优化器将子查询收缩到仅仅是存在性检查的程度。那么,明确使用
EXISTS
是否可以提高性能

SELECT t1.*
       FROM test t1
       WHERE EXISTS (SELECT *
                            FROM test t2
                            WHERE t2.id = ?)
             AND t1.id = ?
              OR NOT EXISTS (SELECT *
                                    FROM test t2
                                    WHERE t2.id = ?)
                 AND t1.id = 0;
                 
无论哪种方式,您都需要
(id)
上的索引