我在表格中有两个列名foo
和bar
。我想在X
和Y
的条件下返回任何返回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
此处X
和Y
是替换到查询中的变量。它们都不会同时为空,所以我们不关心第一个条件。但如果一个为空,则条件检查另一个(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
可能包含空值。
答案 0 :(得分:3)
您可以通过观察X, foo
对独立于Y, bar
对来简化条件。因此,您可以按如下方式简化条件:
WHERE (X is NULL OR foo=X) AND (Y is NULL OR bar=Y)