Вопрос

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?

Это было полезно?

Решение

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

Другие советы

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
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top