三个表关系SQL选择

时间:2014-08-18 01:36:34

标签: sql relational

我正在学习SQL,所以非常感谢帮助。

我有三个表:leagueplayerteam

  • leagueplayer是多对多的(因为玩家可以参加多个联赛)
  • teamplayer是多对多的(因为玩家可以在多个联盟的团队中)
  • leagueteam是一对多。

我有以下表格ID:

league.id  ----. league_has_player (league_id, player_id) .------   player.id
team.id    ----. team_has_player (team_id, player_id)     .-----  player.id
league     ----. team.id (team.league_id)

我希望联盟中所有不属于联盟球队的球员。

这是我破碎的尝试。

Select *
from player p,
    join team t on t.league_id = l.id 
    join league l on league.id = 2
where p.id = league_has_player.player_id and
     not in (select team_has_player.player_id from team_has_player)

2 个答案:

答案 0 :(得分:1)

我认为你正在尝试更多这样的事情。正如一些评论指出的那样,您的表架构并不清楚。但这是我从你的尝试中得到的印象。

DECALRE @leagueId...

SELECT *
FROM player
WHERE player.id IN (SELECT player_id
                    FROM league_has_player
                    WHERE league_id = @leagueId) AND
      player.id NOT IN (SELECT player_id
                        FROM team_has_player
                            INNER JOIN team ON team.Id = team_has_player.team_id
                        WHERE team.league_id = @leagueId)

答案 1 :(得分:0)

让所有在联盟注册的球员都不属于联盟中的球队。

SELECT p.*, lp.league_id
FROM player p
JOIN league_has_player lp ON lp.player_id = p.id
WHERE NOT EXISTS (select 1 
                  FROM team_has_player tp
                  JOIN team t ON t.id = tp.team_id
                  AND tp.player_id = p.player_id
                  AND t.league_id = lp.league_id)