我想分享一下這個簡單概括Joel的優秀答案。這裏的想法是能夠將任意'target'子表作爲表值參數或split分隔字符串傳遞給過程。雖然這很好,但也可以使用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
我已指定數據庫。我只是假定解決方案是數據庫不可知的,但我不需要它。 –
遞歸CTE是ANSI標準,但實現滯後 - 只有3 dbs支持'WITH':Oracle,SQL Server和DB2。 –