sql - SQL Select Query 组合两个查询 if/else, null, empty input
问题描述
例如我有一张桌子
State | Zip | CategoryID | ProductID
FL |12345| 2 | 3
GA |98765| 1 | 5
GA |98765| 1 | 4
我的目标是提出一个与 state、zip、categoryID 和 productID 匹配的查询。但是,我对类别 2 ProductID 的输入可能是 null 或来自用户的空字符串,因为并不总是有与输入关联的 productID。如果 categoryID == 2,它并不真正关心具体的 productID。但是如果 categoryID == 1,它关心的是 productID。如果它的类别 1 是否等于输入或 null 或空字符串并且类别 2 检查产品 ID,是否有我可以做的 if/else?或者有没有办法可以将这两个查询合二为一?
如果类别 2,productID 的输入可以是 3,但也可以是 null 或空字符串。所以,如果它是 null、空字符串或 3。我需要它返回。
FL |12345| 2 | 3
select * from locationPurch l
where l.state = :state
and l.zip = :zip
and l.category = :category
如果是类别 1,productID 的输入将始终存在。因此,如果我们查询 productID 4,它应该返回。
GA |98765| 1 | 4
select * from locationPurch l
where l.state = :state
and l.zip = :zip
and l.categoryID = :category
and l.productID = :productID
解决方案
签出此查询:
select *
from locationPurch l
where l.state = :state
and l.zip = :zip
and l.categoryID = :category
and (
l.categoryID = 2 or l.productID = :productID
)
如果categoryID
是2
,它不会关心操作员的productID
原因or
。如果categoryID
是任何其他值(包括1
),它将检查productID
afteror
运算符。
为此,操作数用括号括起来,并与where子句的其余部分相连接。
推荐阅读
- c# - 四元数lookRotation - 向上不起作用
- java - 为什么我无法从之前设置的单例数组中获取数据?
- android - 无法解析 gradle 的外部依赖
- r - 我如何将符号转换为颜色编码闪亮的应用程序
- anylogic - 当行人使用anylogic进入时,如何从PedSource设置速度后在退出期间更改行人的速度?
- python - 无法在 python 中使用 selenium 在网页中加载“显示更多”?
- http - 有没有办法为多个 http 请求设置令牌?
- r - 使用列表列或嵌套 data.frame 测试小标题的相等性
- python - 保存多个数据,没有重复数据 sqlite sqlachemy flask
- c# - 需要如何使用 TransactionScope 修复“Ora-02048”