不确定“按连接分组”是什么意思-我认为没有:group by
您没有指定您的 DBMS,所以这是 ANSI SQL:
with search_values (val) as (
values (7), (2)
)
-- first part gets all those that do have the search values
-- but will also include those rows that have more than the searched ones
select a
from data
where b in (select val from search_values)
group by a
having count(distinct b) = (select count(*) from search_values)
intersect
-- the intersect then filters out those that have exactly the search values
select a
from data
group by a
having count(distinct b) = (select count(*) from search_values);
SQLFiddle 示例:http ://sqlfiddle.com/#!15/dae93/1
对“搜索值”使用 CTE 可以避免重复它们,并避免“硬编码”要搜索的项目数。如果您寻找 7、2、3,您只需向 CTE 添加另一个值
intersect
可以用一个相关的子查询重写而不是使用它
with search_values (val) as (
values (7), (2)
)
select d1.a
from data d1
where d1.b in (select val from search_values)
group by d1.a
having count(distinct d1.b) = (select count(*) from search_values)
and count(distinct d1.b) = (select count(*) from data d2 where d2.a = d1.a);