2014-11-21 13 views
3

我从表中有两个列名foobar。我想返回任何在XY条件下返回true的行。我想将下表中的条件合并到我的select查询的where部分。SQL - 在两个变量上混合使用XOR和AND的查询

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可能具有空值。

+0

您是否想同时显示两个空变量? – OnlyMAJ 2014-11-21 02:38:53

+0

@OnlyMAJ永远不应该是这样。 – Julio 2014-11-21 04:55:38

回答

3

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

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

他们不幸可以为空。 – Julio 2014-11-21 02:35:45

+0

@Julio我编辑了答案来简化条件。这也适用于可空列。 – dasblinkenlight 2014-11-21 02:39:26

+0

辉煌,看起来不错。 – radar 2014-11-21 02:42:07