在过滤条件中使用OR子句 - Oracle

时间:2013-09-29 10:41:54

标签: sql oracle

我有以下要求,其中SQL必须根据少数OR条件过滤记录。

Table 1
**********
S   A       B
1   Crow    Bird 
2   Apple   Fruit  
3   Orange  Fruit
4   Fox     Animal 
4   Dog     Animal 
4   Cat     Animal 
5   Apple   Mobile 
6   Apple   Product

Table 2
*********
S   A       B
1   Crow    Bird

在表S,A,B

上连接表1左连接表2

在应用这些过滤器后拉取记录

  1. Table2.A is NULL
  2. ((Table1.B='FRUIT' or Table1.B='Mobile') and (Table1.A<>'Apple'))
  3. ((Table1.B='Animal') and ( Table1.A='Fox' or Table1.A='Dog'))
  4. 所以最终的输出看起来像

    S   A   B
    1   Crow    Bird - Filtered Out by Condition 1 
    2   Apple   Fruit  -Filtered Out by Condition2
    3   Orange  Fruit
    4   Fox     Animal 
    4   Dog     Animal 
    4   Cat     Animal - Filtered out by Condition 3
    5   Apple   Mobile - Filtered Out by Condition2
    6   Apple   Product
    

    我尝试了下面的查询,但它返回了错误的结果。

    Select T1.S, T1.A, T1.B 
    from (Select * from Table1 ) T1 
    left join ( Select * from Table 2 ) T2 
    on T1.S=T2.S and T1.A = T2.A and T1.B = T2.B 
    where ( ( T2.A is NULL) or ((T1.B='FRUIT' or T1.B='Mobile') 
      and (T1.A<>'Apple')) or ( ((T1.B='Animal') 
      and ( T1.A='Fox' or T1.A='Dog')) ) ) 
    

1 个答案:

答案 0 :(得分:1)

要诊断问题的根源,请运行以下查询:

Select T1.S, T1.A, T1.B, T2.A as T2_A,
      CASE WHEN T2.A is NULL 
           THEN 'TRUE'
           ELSE 'FALSE'
      END filter1,
      CASE WHEN (T1.B='Fruit' or T1.B='Mobile') AND (T1.A<>'Apple')
           THEN 'TRUE'
           ELSE 'FALSE'
      END filter2,
      CASE WHEN ((T1.B='Animal') and ( T1.A='Fox' or T1.A='Dog'))
           THEN 'TRUE'
           ELSE 'FALSE'
      END filter3  
from (Select * from Table1 ) T1 
left join ( Select * from Table2 ) T2 
on ( T1.S=T2.S and T1.A = T2.A and T1.B = T2.B )
order by t1.s
;

查询显示连接结果,计算每个过滤条件的值,并显示每行和每个过滤器的真/假值。
看到此演示:http://www.sqlfiddle.com/#!4/16c20/20

我认为你的查询工作正常,它给你第一行的desider结果:

1   Crow    Bird - Filtered Out by Condition 1  

但是此行不符合您显示的任何条件。