开发者

SQL Server - Query Help

I have the following 3 tables

Teams (TeamID int, TeamName varchar(200)) - Tea开发者_StackOverflowmID is identity col
Users (UserID int, Username varchar(200)) - UserID is identity col
UsersTeams (ID int, UserID int, TeamID int) - Table has FK references to the 2 tables above

The table UsersTeams is used to keep a record of all teams a user is a member of. I want to find a way, given a user id, to list all teams which a user is not a member of.

Could anyone help?

Regards


You could use not exists:

select  *
from    teams t
where   not exists
        (
        select  *
        from    UserTeams ut
        join    User u
        on      u.UserId = ut.UserId
        where   t.TeamId = ut.TeamID
                and Users.Username = 'TheUser'
        )


DECLARE @UserID INT;

SET @UserID = 1;

SELECT
  *
FROM Teams
WHERE TeamID NOT IN (SELECT TeamID FROM UserTeams WHERE UserID = @UserID)


A join with <> condition might perform better.

DECLARE @UserID INT
SET @UserID = 1   

SELECT Teams.TeamID, Teams.TeamName FROM Teams
INNER JOIN UsersTeams 
ON Teams.TeamID <> UsersTeams.TeamID
WHERE UsersTeams.UserID = @UserID
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜