SQL Server 2008 - 通过分组查看一个表中的行是否存在于另一个表中的最快方法



我正在尝试找到最快的方法来查找@Table2中包含@Table1所有行的所有项目。 例如,给定以下数据,答案应仅为项目 ID = 1,因为它包含@Table1中的所有行。 项目2应该被排除在外,因为它不包含曼彻斯特。

declare @Table1 table (country varchar(50), city varchar(50))
insert into @Table1 (country, city) values ('United Kingdom', 'London');
insert into @Table1 (country, city) values ('United Kingdom', 'Birmingham');
insert into @Table1 (country, city) values ('United Kingdom', 'Manchester');

declare @Table2 table (projectid int, country varchar(50), city varchar(50))
insert into @Table2 (projectid, country, city) values (1, 'United Kingdom', 'London');
insert into @Table2 (projectid, country, city) values (1, 'United Kingdom', 'Birmingham');
insert into @Table2 (projectid, country, city) values (1, 'United Kingdom', 'Manchester');
insert into @Table2 (projectid, country, city) values (1, 'United Kingdom', 'Liverpool');
insert into @Table2 (projectid, country, city) values (2, 'United Kingdom', 'London');
insert into @Table2 (projectid, country, city) values (2, 'United Kingdom', 'Birmingham');
insert into @Table2 (projectid, country, city) values (2, 'United Kingdom', 'Liverpool');
select * from @Table1
select * from @Table2

我已经研究了一点 EXCEPT (这篇文章很有帮助(,但只能在不使用项目 ID 的情况下让它工作。 有一些干净的SQL代码可以提供帮助吗? 在我的数据库中,我希望最多有 100,000 行。

非常感谢

根据我认为我理解的要求,这是做到这一点的一种方法。

select t2.projectid
from @Table1 t1
join @Table2 t2 on t1.country = t2.country 
    and t1.city = t2.city
group by t2.projectid
having count(distinct t2.country + t2.city) = (select count(*) from @Table1)

相关内容

最新更新