Rails migration index for joined tables
I'm using rails 3 and my production db is postgres on Heroku. How do I create a proper index开发者_开发知识库 for this query? I don't know how to create one for the inner join that's happening.
SELECT "plans".* FROM "plans"
INNER JOIN "schedules"
ON "plans".schedule_id = "schedules".id
WHERE (("schedules".user_id = 4))
You should be able to add an index on schedules.user_id:
add_index :schedules, :user_id
... and another index for plans by schedule:
add_index :plans, :schedule_id
Additionally, if you're trying to load all the schedules w/ associated plans you should probably use a left join:
select plans.*
from schedules
left join plans on plans.schedule_id = schedule.id
where schedules.user_id = 4
I think the left join will be correct for what you want here.
精彩评论