检查n个用户是否在同一个房间

时间:2013-05-29 22:10:01

标签: php mysql relational-division

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

但我认为这太过分了。有什么想法吗?

2 个答案:

答案 0 :(得分: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 with Demo

答案 1 :(得分: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