本文介绍了查找所有没有关联的记录的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个团队表和一个球员表,我想找到所有没有关联球员的球队.球员表通过 team_id 列关联.我为此使用 Ruby on Rails,所以我有一个团队和一个玩家模型.

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.

推荐答案

使用左连接可能会更好:

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

或者使用 ARel(感谢 JasonKing 的评论):

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

Team.includes(:players).where('players.team_id IS NULL')

这篇关于查找所有没有关联的记录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-19 06:46