2016-11-23 38 views
0

我有3張桌子,一個給球員,一個給球隊,還有一個給球隊分配球員。我試圖找到所有不在國際象棋隊的球員。我嘗試以下我如何在sql-server中修改這個選擇來包含不在任何團隊中的玩家?

SELECT 
    TP.intPlayerID 
    ,TP.strLastName + ', ' + TP.strFirstName AS strPlayer 
FROM 
    TPlayers     AS TP 
     JOIN TTeamPlayers  AS TTP 
      JOIN TTeams   AS TT 
      ON (TTP.intTeamID = TT.intTeamID) 
     ON (TP.intPlayerID = TTP.intPlayerID) 
WHERE 
    --TTP.intTeamID <> 2 no difference noticed 
    TTP.intTeamID != 2 --hard code for chess team 
ORDER BY 
    strPlayer 

它給我回的球員其他球隊,即使他們是在圍棋隊太強了,它並沒有給我使不上任何一支球隊的所有球員。我感覺好像我應該在這裏的某個地方有個子問題,傾向於在哪裏。我嘗試使用NOT EXISTS,但無法使語法爲我工作。如果您希望其他信息(例如我使用的表格或插入信息)告訴我,我將編輯問題以包含它。

回答

0

您可以嘗試使用NOT IN如下:

create table #Players 
(PlayerId int identity(1,1), 
Name varchar(10)); 


create table #Teams 
(TeamId int identity(1,1), 
Game varchar(30)); 

create table #TeamPlayers 
(TeamId int, 
PlayerId int); 

insert into #Players (Name) 
values ('a'),('b'),('c'),('d'),('e'); 

select * from #Players; 

insert into #Teams (Game) 
values ('No Team'),('Cricket'),('Chess'), ('Tennis'),('BasketBall'); 

select * from #Teams; 

insert into #TeamPlayers (TeamId,PlayerId) 
values (1,2), (2,1),(3,3),(4,3),(4,4),(5,5), (6,3); 

select * from #TeamPlayers; 

select * 
from #Players as P 
where p.PlayerId not in 
    (
     select p.PlayerId 
     from #Players as P 
     inner join #TeamPlayers as tp 
     on p.PlayerId=tp.PlayerId 
     inner join #Teams as t 
     on tp.TeamId =t.TeamId 
     where t.TeamId=3 
    ); 
+0

完美。 –

相關問題