查找时严格多对一匹配 Table

Strict Match Many to One on Lookup Table

这一直让我和我的团队陷入困境。我无法编写严格匹配具有特定查找排列的单个记录的查询。

我们有一个查找 table

room_member_lookup:

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

我需要用确切的成员列表匹配一个房间,但我在堆栈溢出时尝试的所有其他内容仍然匹配房间 A,即使我要求一个只有 Josh 和 Kyle 的房间

我试过

这样的查询
SELECT room FROM room_member_lookup
WHERE member IN (Josh, Michael)
GROUP BY room
HAVING COUNT(1) = 2

然而这仍然是 return 房间 A,即使它有 3 个成员我需要一个精确的成员排列并且匹配房间甚至不部分。

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

根据 SQL 方言,可以构建动态 table(CTE 或 select .. union all)来保存成员集(例如 Monica 和 Kyle) ),然后使用 MINUS/EXCEPT sql 运算符寻找集合等价。