我有3张桌子
User (UserID)
ROOM (RoomID, UserID) ---the userID is the host
RoomMember (RMid, RoomID, UserID) ---the UserID is the people inside the room
这是1个用户主持房间的示例。 然后房间成员是房间里面的人。 现在,我想邀请更多不在会议室内的会员。 如何编写查询以查找不在房间内且不是房间主人的人。
用于SQL asp.net C#查询 我不确定如何使用内部连接。
答案 0 :(得分:1)
有很多方法可以做到这一点,但最简单的方法甚至不需要INNER JOIN
:
DECLARE @RoomID INT = 101 -- or whatever room
SELECT * FROM [User]
WHERE UserId NOT IN (SELECT UserId FROM ROOM WHERE RoomID = @RoomID)
AND UserID NOT IN (SELECT UserId FROM RoomMember WHERE RoomID = @RoomID)
这可以通过排除保留房间的用户,也排除已经是房间成员的所有用户。
实例:http://sqlfiddle.com/#!6/46143/6
您可以更进一步,首先在CTE中建立“排除”成员列表,然后只做一个NOT IN
:
DECLARE @RoomID INT = 101 -- or whatever room
;WITH RoomUsers
AS
(
SELECT UserId FROM ROOM WHERE RoomID = @RoomID
UNION
SELECT UserId FROM RoomMember WHERE RoomID = @RoomID
)
SELECT * FROM [User]
WHERE UserId NOT IN (SELECT userId FROM RoomUsers)