T-SQL - How to write query to get records that match ALL records in a many to many join

本秂侑毒 提交于 2019-12-01 19:47:33
select person_id, count(*) from groupmembership
where group_id in ([your list of group ids])
group by person_id
having count(*) = [size of your list of group ids]

Edited: thank you dotjoe!

Basically you are looking for Persons for whom there is no group he is not a member of, so

select *
from Person p
where not exists (
    select 1
    from Group g
    where not exists (
        select 1
        from GroupMembership gm
        where gm.PersonID = p.ID
        and gm.GroupID = g.ID
    )
)

You're basically not going to avoid "dynamic" SQL in the sense of dynamically generating the query at query time. There's no way to hand a list around in SQL (well, there is, table variables, but getting them into the system from C# is either impossible (2005 & below) or else annoying (2008)).

One way that you could do it with multiple queries is to insert your list into a work table (probably a process-keyed table) and join against that table. The only other option would be to use a dynamic query such as the ones specified by Jonathan and hongliang.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!