Finding all records without associated ones

后端 未结 4 1955
野性不改
野性不改 2020-12-06 01:49

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_i

相关标签:
4条回答
  • 2020-12-06 02:25

    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')
    
    0 讨论(0)
  • 2020-12-06 02:36

    Something like this:

    select * from teams
    where id not in (select distinct team_id from players)
    
    0 讨论(0)
  • 2020-12-06 02:36

    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)
    
    0 讨论(0)
  • 2020-12-06 02:36

    You should generally be able to do an outer join from parent to child and check for a null value in a field in the child that is not null-able. This is generally faster than a 'not in' or 'not exists'. This may not work on all databases.

    0 讨论(0)
提交回复
热议问题