我想提取 A 列,C 中的所有元素都在 B 中。
T1:
+-----+-----+
| A | B |
+-----+-----+
| a | 1 |
| a | 2 |
| a | 3 |
| b | 1 |
| b | 2 |
| b | 4 |
| c | 2 |
| c | 3 |
| c | 4 |
+-----+-----+
T2:
+-----+
| C |
+-----+
| 2 |
| 4 |
+-----+
例如选择b是因为有(b, 2)和(b, 4)记录。但是,a 没有被选中,因为没有 (a, 4)。
所需的输出:
+-----+
| A |
+-----+
| b |
| c |
+-----+
我应该为条件写什么?
select A
from T1
where ...
答案 0 :(得分:0)
这应该可以实现您的目标。
SELECT A
FROM (
SELECT A, COUNT(*) [Count]
FROM T1
WHERE B IN (SELECT C FROM T2)
GROUP BY A) t
WHERE t.[Count] >= (SELECT COUNT(*) FROM T2)
答案 1 :(得分:0)
一种方法将两个表连接在一起,然后计算匹配项:
select t1.a
from t1 join
t2
on t1.b = t2.c
group by t1.a
having count(*) = (select count(*) from t2);
注意:如果 t1
可以有重复的行,请使用:
having count(distinct t1.b) = (select count(*) from t2)