开发者

Rails migration index for joined tables

开发者 https://www.devze.com 2023-04-03 17:46 出处:网络
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.

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.

0

精彩评论

暂无评论...
验证码 换一张
取 消