【问题标题】:PostgreSQL verify table value and return else return default valuePostgreSQL 验证表值并返回否则返回默认值
【发布时间】: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


    【解决方案1】:

    嗯,我不认为你的方法有一半是坏的......这取决于优化器将子查询缩小到仅仅是存在检查的程度。那么也许显式使用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) 上建立索引。

    【讨论】:

      猜你喜欢
      • 2021-11-16
      • 2018-12-12
      • 2021-02-09
      • 1970-01-01
      • 2013-04-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多