gpt4 book ai didi

sql - PostgreSQL - 有条件地从 WHERE 子句中排除语句

转载 作者:行者123 更新时间:2023-11-29 14:31:26 26 4
gpt4 key购买 nike

我正在使用 PL/pgSQL(PostgreSQL 版本 10),想知道是否有办法从 WHERE 子句中排除语句。

我的代码:

WHERE 
(
e.priority >= priority_from AND
e.priority <= priority_to
) AND
v.id = vocabulary_id_ AND
e.text LIKE '%' || search_phrase || '%'
;

如果参数 vocabulary_id_ 的值为 0null - 查询返回 0 条记录,因为没有这样的 vocabularyId 等于 0null

如果我使用 IF ELSE 语句 - 我最终会得到 2 个几乎相同的查询 - 一个带有 v.id = vocabulary_id_ AND 部分,另一个没有

有没有使用PL/pgSQL 语法的简单方法来排除这部分?

最佳答案

你可以用这个

WHERE 
(
e.priority >= priority_from AND
e.priority <= priority_to
) And (V.id = vocabulary_id_ or vocabulary_id_ is null or vocabulary_id_ = 0) and
e.text LIKE '%' || search_phrase || '%'
;

只是补充一下,至少对于 SQL Server,虽然这很方便,但至少对于 SQL Server,这些类型的查询有时会导致性能欠佳。我不知道 postgres 是否属于这种情况。

关于sql - PostgreSQL - 有条件地从 WHERE 子句中排除语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51235621/

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