连接表的Rails迁移索引

时间:2011-09-08 12:23:34

标签: sql ruby-on-rails postgresql

我正在使用rails 3,我的生产数据库是Heroku上的postgres。如何为此查询创建正确的索引?我不知道如何为正在发生的内部联接创建一个。

SELECT "plans".* FROM "plans" 
INNER JOIN "schedules" 
ON "plans".schedule_id = "schedules".id 
WHERE (("schedules".user_id = 4))

1 个答案:

答案 0 :(得分:0)

您应该能够在schedules.user_id上添加索引:

add_index :schedules, :user_id

......以及按计划划分的另一个计划索引:

add_index :plans, :schedule_id

此外,如果您尝试加载所有具有关联计划的计划,您应该使用左连接:

select plans.*
  from schedules
  left join plans on plans.schedule_id = schedule.id
  where schedules.user_id = 4

我认为左边的连接对于你想要的东西是正确的。