我想根据两个变量来过滤列,即(在伪代码中):
我尝试过以下PL / SQL语句:
select * from table t where
((t.column1 is not null and t.column1=filter1 and t.column2 is not null and t.column2=t.filter2) -- condition A
or (t.column1 is not null and t.column1=filter1) -- condition B
or (t.column2 is not null and t.column2=filter2)); -- condition C
虽然我已经检查过它是否独立地适用于每个条件,但它并不适用于所有三个条件。 例如:
有什么问题?请帮助:)
答案 0 :(得分:0)
当它们为空时,您应该反思:
select *
from table t
where (t.column1 is null or t.column1=filter1)
and
(t.column2 is null or t.column2=filter2);
考虑这个条件:
(t.column1 is null or t.column1=filter1)
如果t.column1 is null
为真,那么t.column1=filter1
甚至不会被评估,因为true or whatever
始终是true
。这意味着,仅当t.column1=filter1
不为空时才评估t.column1
。
让我们测试每种情况。
column1 = null,column2 = null
查询返回所有行,因为条件为where (true or t.column1=filter1) and (true or t.column2=filter2)
,简化为
where true and true
column1 = null,column2!= null
条件为where (true) and (false or t.column2=filter2)
,简化为
where t.column2=filter2
column1!= null,column2 = null
条件为where (false or t.column1=filter1) and (true)
,简化为
where t.column1=filter1
column1!= null,column2!= null
条件为where (false or t.column1=filter1) and (false or t.column2=filter2)
,简化为
where t.column1=filter1 and t.column2=filter2
答案 1 :(得分:0)
试试这个:
select *
from table t
where ((t.column1 = filter1 and t.column2 = t.filter2) -- condition 1
or (t.column1 = filter1 and t.column2 is null ) -- condition 2
or (t.column2 = filter2 and t.column1 is null)); -- condition 3
过滤器值不应为null,否则您必须使用nvl,如下所示:
select *
from table t
where ((t.column1 = nvl(filter1,-1) and t.column2 = nvl(t.filter2, -1) ) -- condition 1
or (t.column1 = nvl(filter1,-1) and t.column2 is null ) -- condition 2
or (t.column2 = nvl(filter2,-1) and t.column1 is null)); -- condition 3