简体   繁体   English

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

[英]Select complete matching between two table

I have two tables 我有两张桌子

t1 T1

col1    col2
A        1
A        2 
B        1
C        2

t2 T2

col1
1
2

I want to retrieve the records in tab1 which match all the records in tab2, 我想在tab1中检索与tab2中的所有记录匹配的记录,

For the given scenario, I want to output A only because it has both 1 and 2 in col2 where as B and C has only a 1 or a 2 (not both). 对于给定的情况,我只想输出A,因为在col2中它既有1又有2,而B和C却只有1或2(不是全部)。

You can write the query this way: 您可以通过以下方式编写查询:

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);

This counts the number of matching values in the first table and compares it to the total number of values in the table. 这将计算第一个表中匹配值的数量,并将其与表中的总值进行比较。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM