我有两个列名foo
,bar
来自一个表。我想返回任何在X
和Y
上放置的条件返回 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
这里的X
和Y
是替换到查询中的变量。它们永远不会同时为 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)
编辑注意:foo
和bar
可能具有空值。
您可以通过观察X, foo
对独立于Y, bar
对来简化条件。因此,您可以按如下方式简化条件:
WHERE (X is NULL OR foo=X) AND (Y is NULL OR bar=Y)