1

我有一个 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

但我认为这太过分了。有任何想法吗?

4

2 回答 2

1
SELECT r1.roomID
FROM user_to_room r1
INNER JOIN user_to_room r2 ON r1.roomID=r2.roomID
LEFT OUTER JOIN user_to_room r3 ON r1.roomID=r3.roomID AND r3.userID NOT IN (2,5)
WHERE r1.userID=2 AND r2.userID=5
  AND r3.roomID IS NULL
于 2013-05-29T22:44:43.437 回答
1

您应该能够使用与第一个查询相同的查询,但添加一个过滤器以排除用户在 2、5 之外的任何房间:

select roomId
from user_to_room
where userid in (2,5)
  and roomid not in (select roomid
                     from user_to_room
                     where userid not in (2, 5))
group by roomId
having count(distinct userid) = 2;

请参阅带有演示的 SQL Fiddle

于 2013-05-29T22:33:39.387 回答