-1

I'm learning SQL, so help is greatly appreciated.

I have three tables: league, player and team

  • league and player is many to many (as a player can be in more than one league)
  • team and player is many to many (as a player can be on a team in multiple leagues)
  • league and team is one to many.

I have the following table ids:

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)

I want to get all the players in the league who are not on a team in the league.

Here's my broken attempt.

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)
Matthew Haugen
  • 12,916
  • 5
  • 38
  • 54
Haymps
  • 91
  • 9

2 Answers2

1

I think you're trying more for something like this. As a couple comments have pointed out, your table schema isn't clear. But this is the impression I get from your attempt.

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)
Matthew Haugen
  • 12,916
  • 5
  • 38
  • 54
0

Get all the players registered for the league, where they don't belong to a team in the league.

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)
simo.3792
  • 2,102
  • 1
  • 17
  • 29