1

我有一个 user_to_room 表

roomID | userID 

我现在想检查是否有 2 个用户在同一个房间

SELECT roomID
FROM   room_to_user
WHERE  userID = 1 AND 2

如何通过 JOIN 实现这一目标?

4

3 回答 3

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;

演示

于 2013-05-12T19:57:39.867 回答
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

在这里查看演示

于 2013-05-12T19:59:37.190 回答
0

您可以使用的另一个解决方案是:

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

这将计算满足条件的每个房间的 DISTINCT 用户数userID IN (2,3)。如果计数为 2,则表示 userID 2 和 userID 3 都在同一个房间。

于 2013-05-12T20:24:22.597 回答