gpt4 book ai didi

sql - postgreSQL 查询中的可选条件

转载 作者:行者123 更新时间:2023-11-29 11:43:25 24 4
gpt4 key购买 nike

我需要创建一个带有可选参数的过程,并且只有当它们不为空时才使用它们

我当前的查询如下:

SELECT * FROM sth WHERE
(arg1 IS NULL OR sth.c1 = arg1) AND
(arg2 IS NULL OR sth.c2 = arg2) AND
(arg3 IS NULL OR sth.c3 > arg3) AND
(arg4 IS NULL OR sth.c4 < arg4)

我正在想办法让它看起来更好/更短。我的第一枪是:

SELECT * FROM sth WHERE
COALESCE(sth.c1 = arg1, 't') AND
COALESCE(sth.c2 = arg2, 't') AND
COALESCE(sth.c3 > arg3, 't') AND
COALESCE(sth.c4 < arg4, 't');

但我不确定这看起来是否更好。您知道这方面的任何有用技巧吗?

最佳答案

保持原样。使用 coalesce 会阻止查询规划器正常工作,并且您最终会得到糟糕的查询计划。

据我所知,以下表达式将使用 btree 索引:

  • col = 'val'
  • col is null

以下表达式不会使用 btree 索引:

  • col is [not] 'val'
  • (col = 'val') is [not] <true | false | null>
  • col is [not] distinct from 'val'
  • coalesce(col, 'val') = 'val'
  • coalesce(col = 'val', <true | false | null>)

关于sql - postgreSQL 查询中的可选条件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20265713/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com