从DB2表中筛选具有多个搜索值组合的行

vbkedwbf  于 2022-11-07  发布在  DB2
关注(0)|答案(1)|浏览(171)

假设我有一个由5列组成的DB2表,我应该如何根据每个列的已知值的任意组合来过滤行呢?
如果我对5列中的每一列都有一个搜索值,并且我想返回与所有这些值匹配的行,那么我可以简单地按以下条件进行筛选

SELECT * FROM TABLE
  WHERE A = value1 and B = value2 and C = value3 and D = value 4 and E = value 5

但是,如果我只有来自列A和B、A和C、A B和C等的搜索值,该怎么办?如何创建一个WHERE子句,使其能够根据我拥有的可用搜索值筛选返回的行?
如何实现输入的搜索条件越多,在一个WHERE子句中返回的行就越少的想法?

ar5n3qh5

ar5n3qh51#

这取决于特定的数据库解析器,但是如果您有五列abcde和五个可能为空的参数p0p1p2p3p4,则查询可以采用以下形式:

select *
from t
where (a = :p0 or :p0 is null)
  and (b = :p1 or :p1 is null)
  and (c = :p2 or :p2 is null)
  and (d = :p3 or :p3 is null)
  and (e = :p4 or :p4 is null)

使用JDBC时,参数化查询可能如下所示:

select *
from t
where (a = ? or ? is null)
  and (b = ? or ? is null)
  and (c = ? or ? is null)
  and (d = ? or ? is null)
  and (e = ? or ? is null)

请记住,像这样的查询提供的优化机会很少。很可能引擎每次都需要扫描整个堆。

相关问题