我有3个桌子,一个用于球员,一个用于球队,一个用于将球员分配到球队。我试图找到不在国际象棋队的所有球员。我尝试了以下
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 :(得分: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
);