Sql 选择两个表之间的完全匹配

Sql 选择两个表之间的完全匹配,sql,Sql,我有两张桌子 t1 t2 我想检索tab1中与tab2中所有记录匹配的记录 对于给定的场景,我只想输出A,因为它在col2中同时有1和2,而as B和C只有1或2(不是两者)。您可以这样编写查询: select t1.col1 from t1 join t2 on t1.col2 = t2.col1 group by t1.col1 having count(distinct t1.col2) = (select count(distinct t2.col1) from t2

我有两张桌子

t1

t2

我想检索tab1中与tab2中所有记录匹配的记录


对于给定的场景,我只想输出A,因为它在col2中同时有1和2,而as B和C只有1或2(不是两者)。

您可以这样编写查询:

select t1.col1
from t1 join
     t2
     on t1.col2 = t2.col1
group by t1.col1
having count(distinct t1.col2) = (select count(distinct t2.col1) from t2);

这将统计第一个表中匹配值的数量,并将其与表中的值总数进行比较。

您使用的是什么DBM程序?MSSQL?MySQL?该程序将影响此查询的语法,以及我们可以使用哪些函数来帮助您…您的
t1.col2
中可以有多少不同的值?到目前为止,你都试过什么?
col1
1
2
select t1.col1
from t1 join
     t2
     on t1.col2 = t2.col1
group by t1.col1
having count(distinct t1.col2) = (select count(distinct t2.col1) from t2);