我有一个user_to_room表
roomID | userID
我现在想检查,如果2个用户在同一个房间
SELECT roomID
FROM room_to_user
WHERE userID = 1 AND 2
如何通过JOIN实现这一目标?
答案 0 :(得分:3)
自我加入:
SELECT DISTINCT u1.roomID AS roomID
FROM user_to_room u1, user_to_room u2
WHERE u1.userID = 1 AND u2.userID = 2
AND u1.roomID = u2.roomID;
请参阅demo。
答案 1 :(得分:2)
您还可以进行以下查询:
CREATE TABLE user_to_room (roomID INT, userID INT);
INSERT INTO user_to_room VALUES (101, 2);
INSERT INTO user_to_room VALUES (102, 3);
INSERT INTO user_to_room VALUES (102, 4);
select distinct roomid
from user_to_room a where exists
(select top 1 1 from user_to_room where roomid = a.roomid and userid =3)
and userid = 4
检查demo此处
答案 2 :(得分:0)
您可以使用的另一种解决方案是:
SELECT roomID
FROM user_to_room
WHERE userID IN (2,3)
GROUP BY roomID
HAVING COUNT(DISTINCT userID)=2
这将计算满足condiction userID IN (2,3)
的每个房间的DISTINCT用户数。如果计数为2,则表示userID 2和userID 3都在同一个房间内。