我想分享乔尔出色答案的这个简单概括。这里的想法是能够将任意“目标”子表作为表值参数或拆分分隔字符串传递到过程中。虽然这很好,但如果有一个使用 LIKE 而不是 IN 匹配的类似查询也很好。
--Parents whose children contain a subset of children
--setup
create table #parent ( id int )
create table #child ( parent_id int, foo varchar(32) )
insert into #parent (id) values (1)
insert into #parent (id) values (2)
insert into #parent (id) values (3)
insert into #child (parent_id, foo) values (1, 'buzz')
insert into #child (parent_id, foo) values (1, 'buzz')
insert into #child (parent_id, foo) values (1, 'fizz')
insert into #child (parent_id, foo) values (2, 'buzz')
insert into #child (parent_id, foo) values (2, 'fizz')
insert into #child (parent_id, foo) values (2, 'bang')
insert into #child (parent_id, foo) values (3, 'buzz')
--create in calling procedure
declare @tblTargets table (strTarget varchar(10))
insert into @tblTargets (strTarget) values ('fizz')
insert into @tblTargets (strTarget) values ('buzz')
--select query to be called in procedure;
-- pass @tblTargets in as TVP, or create from delimited string via splitter function
select #parent.id --returns 1 and 2
from #parent
inner join #child on #parent.id = #child.parent_id
where #child.foo in (select strTarget from @tblTargets)
group by #parent.id
having count(distinct #child.foo) = (select COUNT(*) from @tblTargets)
--cleanup
drop table #parent
drop table #child