postgresql - 当PostgreSQL中的where子句为空时,如何不依赖于where子句中的条件进行查询?
问题描述
我想进行一个查询,当条件为空时,结果不取决于 where 子句中的条件,而当条件不为空时,结果取决于条件。
我提出的一个查询是
select * from mytable where (num_lot = :num_lot or :num_lot is null) and date_work between :date_start and :date_stop
当:num_lot
为空时,结果不取决于我想要的 num_lot。但是:date_start
并且:date_stop
为空,没有返回任何行,而不是不依赖于:date_start 和:date_stop。
解决方案
SELECT * FROM mytable WHERE
num_lot=COALESCE(:num_lot,num_lot) AND
date_work BETWEEN COALESCE(:date_start,date_work) and COALESCE(:date_stop,date_work)
当验证值为 NULL 时,它被替换为列值,即始终为真。
推荐阅读
- c# - 在 foreach 循环的字符串列表中添加新项目时更新列表
- c# - Visual Studio 2017 表单
- php - OSX composer 增加内存限制
- android - 不是我创建的 Android 默认 alertdialog 背景颜色
- mysql - 如何将主表与 2 个表连接起来,以获取 2 个表中主表主 ID 的计数以及 codeigniter 中的主表信息
- c# - 从 Firebase 数据库中检索数据并将数据保存在统一上的问题
- typescript - 如何在承诺中使用 sqs.makeUnauthenticatedRequest?
- java - 在文件中存储多个值 - 最佳格式?
- javascript - 如何将数字与香草JavaScript中的数组中的数字匹配?
- c - 在另一个宏中使用字符串宏