动态 SQL - 在两个变量上混合使用 XOR 和 AND 的 WHERE 查询



我有两个列名foobar来自一个表。我想返回任何在XY上放置的条件返回 true 的行。我想将下表中的条件合并到select查询的where部分中。

   X      |    Y     |  conditions
----------+----------+----------------
   null   |   null   | 
 not null |   null   |  foo=X
   null   | not null |  bar=Y
 not null | not null |  foo=X and bar=Y

这里的XY是替换到查询中的变量。它们永远不会同时为 null,所以我们不关心第一个条件。但是,如果一个为空,则条件检查另一个(XOR)。如果两者都不为空,则条件检查两者 (AND)。这是我到目前为止的查询,但是where部分有什么更简单,更干净的吗?

select
      ...
where
     (X is not null and Y is not null and
      foo=X and bar=Y)
  or (X is not null and
      Y is null and foo=X)
  or (X is null and
      Y is not null and bar=Y)

编辑注意:foobar可能具有空值。

您可以通过观察X, foo对独立于Y, bar对来简化条件。因此,您可以按如下方式简化条件:

WHERE (X is NULL OR foo=X) AND (Y is NULL OR bar=Y)