0

这个查询执行得很好:

p = PlayersToTeam.select("id").joins(:player).limit(10).order("players.FirstName")

这个查询导致我的整个系统突然停止:

p = PlayersToTeam.select("id").includes(:player).limit(10).order("players.FirstName")

以下是模型:

class PlayersToTeam < ActiveRecord::Base
  belongs_to :player
  belongs_to :team

  accepts_nested_attributes_for :player
end

class Player < ActiveRecord::Base
  has_many :players_to_teams
  has_many :teams, through: :players_to_teams
end

据我所知,includes做 aLEFT JOINjoins做 a INNER JOINjoins从 Rails输出的查询 (for ) 是:

SELECT players_to_teams.id FROM `players_to_teams` INNER JOIN `players` ON `players`.`id` = `players_to_teams`.`player_id` ORDER BY players.FirstName LIMIT 10

在命令行上执行得很好。

SELECT players_to_teams.id FROM `players_to_teams` LEFT JOIN `players` ON `players`.`id` = `players_to_teams`.`player_id` ORDER BY players.FirstName LIMIT 10

也执行得很好,只需要两倍的时间。

有没有一种有效的方法可以通过 对players_to_teams记录进行排序players?我有一个关于FirstNamefor的索引players

编辑

原来查询需要大量优化才能正常运行。拆分查询是没有重组数据或自定义查询的最佳解决方案

4

2 回答 2

0

需要注意的一件事是,这include将添加第二个数据库访问权限来进行预加载。你应该检查那个看起来像什么(它应该包含一个关于from的大IN声明)。player_idsplayers_to_teams

至于如何避免使用include,如果你只需要来自的名称players,你可以这样做:

PlayersToTeam.select("players_to_teams.id, players.FirstName AS player_name").joins(:player).limit(10).order("players.FirstName")
于 2012-04-11T20:50:38.343 回答
0

您也可以考虑将其拆分为 2(3) 个查询。首先 - 通过连接排序来获取 id:

players_to_teams = PlayersToTeam.select("id").joins(:player).limit(10).order("players.FirstName")

第二个(里面包含 2 个查询)-PlayersToTeams预装玩家。

players_to_teams = PlayersToTeam.include(:player).where(:id => players_to_teams.map(&:id))

因此,在那之后,您将完全初始化players_to_teams并加载和初始化播放器。

于 2012-04-11T21:20:19.557 回答