我有一个 user_to_room 表
roomID | userID
我使用此查询来获取 roomID(取决于 n 个用户 ID)
SELECT roomID
FROM user_to_room
WHERE userID IN (2,5)
GROUP BY roomID
HAVING COUNT(DISTINCT userID)=2
不工作演示:http ://www.sqlfiddle.com/#!3/00b4a/1/0
(取自https://stackoverflow.com/a/16511691/1405318)
但是这个查询也会返回这两个用户所在的房间以及另一个随机用户。我需要一个查询,它只返回给定用户 (2,3) 所在的房间。
一个可行的解决方案是
SELECT DISTINCT roomID
FROM user_to_room AS x2
WHERE x2.roomID NOT IN(SELECT DISTINCT roomID
FROM user_to_room
WHERE roomID IN(SELECT DISTINCT roomID
FROM user_to_room
WHERE userID IN ( 5, 2 )
GROUP BY roomID
HAVING Count(DISTINCT userID) = 2)
AND userID NOT IN( 2, 5 ))
AND roomID IN(SELECT DISTINCT roomID
FROM user_to_room
WHERE userID IN ( 5, 2 )
GROUP BY roomID
HAVING Count(DISTINCT userID) = 2)
工作演示:http ://www.sqlfiddle.com/#!3/00b4a/2/0
但我认为这太过分了。有任何想法吗?