首页 > 解决方案 > 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

标签: sqlsql-serveroracle

解决方案


签出此查询:

select *
from locationPurch l
where l.state = :state
  and l.zip = :zip
  and l.categoryID = :category
  and (
    l.categoryID = 2 or l.productID = :productID
  )

如果categoryID2,它不会关心操作员的productID原因or。如果categoryID是任何其他值(包括1),它将检查productIDafteror运算符。

为此,操作数用括号括起来,并where子句的其余部分相连接。


推荐阅读