Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Finding all records without associated ones

I have a teams table and a players table and I'm wanting to find all teams that do not have players associated with them. The players table is associated via a team_id column. I'm using Ruby on Rails for this so I have a Team and a Player model.

like image 852
Ryan Bigg Avatar asked Aug 21 '09 22:08

Ryan Bigg


2 Answers

You'd do that with a NOT EXISTS condition like so:

SELECT *
FROM teams
WHERE NOT EXISTS (SELECT 1 FROM players WHERE players.team_id = teams.team_id)
like image 61
VoteyDisciple Avatar answered Sep 27 '22 01:09

VoteyDisciple


It may perform better doing a left join:

SELECT
teams.*
FROM teams
LEFT JOIN players ON (teams.id = players.team_id)
WHERE
players.team_id IS NULL

Or using ARel (thanks to JasonKing's comment):

Team.includes(:players).where('players.team_id IS NULL')
like image 31
Richard Pistole Avatar answered Sep 24 '22 01:09

Richard Pistole