通过另一个表中的多个列对表进行子集

时间:2017-03-20 19:02:49

标签: sql postgresql exists

从下面的表A中,我想选择A2 = 1的行,并且A1-A3组合在下面的表B中作为B1-B2组合存在。结果应该是表C.我该怎么做?我的实际桌子很大,所以效率很重要。谢谢。

表A

A1   |A2  |A3  |A4
-----+----+----+----
a    |1   |9   |o   
b    |1   |10  |k
c    |0   |2   |d   
d    |0   |12  |f
e    |1   |8   |g   
f    |1   |14  |h
e    |1   |12  |p   

表B

B1   |B2  |B3  
-----+----+----
a    |9   |k    
a    |9   |l  
c    |2   |m   
e    |8   |o  
c    |3   |p   
e    |8   |q  

表C

A1   |A2  |A3  |A4
-----+----+----+----
a    |1   |9   |o   
e    |1   |8   |g   

1 个答案:

答案 0 :(得分:1)

select A1, A2, A3, A4
from   tableA
where  A2 = 1
and    exists (select 1
               from   tableB
               where  B1 = A1
               and    B2 = A3); 

取决于您的表架构:

select     A1, A2, A3, A4
from       tableA
inner join tablaB
on         A1 = B1
and        A3 = B2
where      A2 = 1;