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

时间:2014-11-21 02:26:35

标签: sql dynamic-sql

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

   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是替换到查询中的变量。它们都不会同时为空,所以我们不关心第一个条件。但如果一个为空,则条件检查另一个(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可能包含空值。

1 个答案:

答案 0 :(得分:3)

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

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