这个查询执行得很好:
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 JOIN
和joins
做 a INNER JOIN
。joins
从 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
?我有一个关于FirstName
for的索引players
。
编辑
原来查询需要大量优化才能正常运行。拆分查询是没有重组数据或自定义查询的最佳解决方案