我有一个包含两列ID的表。
TABLE
id1 id2
1 1
1 2
1 3
2 1
2 6
2 2
3 1
3 10
3 3
我想选择与id2s的某个组合匹配的每个id1。
例如,如果我有id2 = [1,2,3]我想返回id1 = [1];
如果我有id2 = [1,6]我想返回id1 = [2];
如果我有id2 = [1]我想返回id1 = [1,2,3]。
有关如何最好地完成此任务的任何建议将不胜感激。
谢谢,
答案 0 :(得分:1)
您可以搜索匹配的id2,并使用count(distinct id2)
验证所有id2是否匹配。计数应该等于id2的数量。对于id2 = [1,2,3],计数应为3:
select id1
from YourTable
where id2 in (1,2,3)
group by id1
having count(distinct id2) = 3;
打印1.对于id2 = [1,6]:
select id1
from YourTable
where id2 in (1,6)
group by id1
having count(distinct id2) = 2;
这打印2.对于id2 = [1]:
select id1
from YourTable
where id2 in (1)
group by id1
having count(distinct id2) = 1;
这会打印1,2,3。
答案 1 :(得分:0)
尝试:
SELECT DISTINCT id1
AS found_id1
FROM table
WHERE id2 IN (1, 2, 3)
你会得到:
DISTINCT id1
--------
1