获取与另一个表中的整个列匹配的元组名称

时间:2017-10-27 19:35:36

标签: sql postgresql

我必须从name中选择每个table1,其中包含与type的{​​{1}}匹配的元组,而无需分组或汇总函数。

table2

从这里开始,它应该输出

 table1        table2
name|type     type|info
 a  | 1         1 | .
 a  | 2         2 | ..
 a  | 3         3 | ...
 b  | 1
 b  | 2  
 b  | 3         
 c  | 2

编辑: 最终做了像

这样的事情
name|
 a  |
 b  |

第二次选择会为表格中没有类型的名称创建一个空值的表格。所以,如果''不在第二个选择中,这意味着它对table2中的每个类型都有一个元组。我想

1 个答案:

答案 0 :(得分:0)

这是一种方法:

select t1.name
from table1 t1
where exists (select 1 from table2 t2 where t2.type = t1.type)
group by t1.name
having count(distinct t1.type) = (select count(distinct t2.type) from table2);

这会将t1过滤到t2中的匹配项。然后计算匹配的数字。

这使用count(distinct),它允许相应表格中的重复项。如果没有重复项,那么只需使用count()