用于查找异常成员的数据库连接逻辑
Database Join Logic for finding exception member
我有3个table
User (UserID)
ROOM (RoomID, UserID) ---the userID is the host
RoomMember (RMid, RoomID, UserID) ---the UserID is the people inside the room
这是 1 位用户主持房间的示例。
那么房间成员就是那些在房间里的人。
现在,我想邀请更多不在房间内的成员。
我如何编写查询来查找那些不在房间内且也不是房间主持人的人。
for SQL asp.net C# 查询
我不确定如何使用 inner Join 来做到这一点。
有很多方法可以做到这一点,但最简单的甚至不需要 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 中建立 "excluded" 成员列表,然后只做一个 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)
我有3个table
User (UserID)
ROOM (RoomID, UserID) ---the userID is the host
RoomMember (RMid, RoomID, UserID) ---the UserID is the people inside the room
这是 1 位用户主持房间的示例。 那么房间成员就是那些在房间里的人。 现在,我想邀请更多不在房间内的成员。 我如何编写查询来查找那些不在房间内且也不是房间主持人的人。
for SQL asp.net C# 查询 我不确定如何使用 inner Join 来做到这一点。
有很多方法可以做到这一点,但最简单的甚至不需要 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 中建立 "excluded" 成员列表,然后只做一个 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)