0

我有以下要求,其中 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'))

所以最终的输出看起来像

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')) ) ) 
4

1 回答 1

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 我认为您的查询工作正常,它为您提供除第一行之外的预期结果:

1   Crow    Bird - Filtered Out by Condition 1  

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

于 2013-09-29T13:42:34.803 回答