Search code examples
sqlone-to-manydistinct-values

Strict Match Many to One on Lookup Table


This has been driving me and my team up the wall. I cannot compose a query that will strict match a single record that has a specific permutation of look ups.

We have a single lookup table

room_member_lookup:

room  | member
---------------
A     | Michael
A     | Josh
A     | Kyle
B     | Kyle
B     | Monica
C     | Michael

I need to match a room with an exact list of members but everything else I've tried on stack overflow will still match room A even if I ask for a room with ONLY Josh and Kyle

I've tried queries like

SELECT room FROM room_member_lookup
WHERE member IN (Josh, Michael)
GROUP BY room
HAVING COUNT(1) = 2

However this will still return room A even though that has 3 members I need a exact member permutation and that matches the room even not partials.


Solution

  • SELECT room 
    FROM room_member_lookup a
    WHERE member IN ('Monica', 'Kyle')
      -- Make sure that the room 'a' has exactly two members
      and (select count(*) 
           from room_member_lookup b 
           where a.room=b.room)=2
    GROUP BY room
    -- and both members are in that room
    HAVING COUNT(1) = 2
    

    Depending on the SQL dialect, one can build a dynamic table (CTE or select .. union all) to hold the member set (Monica and Kyle, for example), and then look for set equivalence using MINUS/EXCEPT sql operators.