合并where子句sql

时间:2014-03-05 17:30:35

标签: sql oracle

我有一个非常有效的select语句因为我使用union all来使其工作而不是正确使用括号或'或'。如果您知道更好的方法来结合这些陈述,请告诉我们:

select * from apples_2014
where value is null
and (date_1 <= '2014-01-21' and date_2 <= '2014-01-21')

union all

select * from apples_2014
where value is null
and (date_1 <= '2014-01-21' and date_2 is null)

union all 

select * from apples_2014
where value is null
and (date_2 <= '2014-01-21' and date_1 is null)

union all

select * from apples_2014
where value is null
and (date_3 <= '2014-01-21' and date_3 is not null)

3 个答案:

答案 0 :(得分:1)

以下内容与您想要的非常相似:

select *
from apples_2014
where value is null and
      ((date_1 <= '2014-01-21' and date_2 <= '2014-01-21') or
       (date_1 <= '2014-01-21' and date_2 is null) or
       (date_2 <= '2014-01-21' and date_1 is null) or
       (date_3 <= '2014-01-21' and date_3 is not null)
      );

但是有一点不同。您的查询有时会多次返回一行,每个条件一次。这只会返回一行。

答案 1 :(得分:0)

   select * from apples_2014
    where 
    value is null
    and (
    (date_1 <= '2014-01-21' and date_2 <= '2014-01-21')
OR (date_1 <= '2014-01-21' and date_2 is null)
    OR (date_2 <= '2014-01-21' and date_1 is null)
    OR (date_3 <= '2014-01-21' and date_3 is not null)
    )

答案 2 :(得分:0)

试试这个

select * from apples_2014
where value is null
   and (
           (date_1 <= '2014-01-21' and date_2 <= '2014-01-21')
           OR (date_1 <= '2014-01-21' and date_2 is null)
           OR (date_2 <= '2014-01-21' and date_1 is null)
           OR (date_3 <= '2014-01-21' and date_3 is not null)
       )