Search code examples
phpmysqlrelational-division

Check if n users are in same room


I have a user_to_room table

roomID | userID 

I used this query to get a roomID (depending on n userIDs)

SELECT   roomID
FROM     user_to_room
WHERE    userID IN (2,5)
GROUP BY roomID
HAVING   COUNT(DISTINCT userID)=2

Not working demo: http://www.sqlfiddle.com/#!3/00b4a/1/0

(taken from https://stackoverflow.com/a/16511691/1405318)

But this query also returns rooms where those two users are in plus another random user. I need a query which only returns the room in which the given users (2,3) are in.

A working solution would be

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)

Working demo: http://www.sqlfiddle.com/#!3/00b4a/2/0

But I think this is way too much. Any ideas?


Solution

  • You should be able to use the same query as your first one but add a filter to exclude any rooms that have users outside of 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;
    

    See SQL Fiddle with Demo