Rails:include vs.:join - Rails :include vs. :joins

问题:

This is more of a "why do things work this way" question rather than a "I don't know how to do this" question... 这更像是“为什么会这样做”这个问题,而不是“我不知道该怎么做”这个问题......

So the gospel on pulling associated records that you know you're going to use is to use :include because you'll get a join and avoid a whole bunch of extra queries: 所以关于拉你知道你将要使用的相关记录的福音是使用:include因为你将获得一个连接并避免一大堆额外的查询:

Post.all(:include => :comments)

However when you look at the logs, there's no join happening: 但是,当您查看日志时,没有发生加入:

Post Load (3.7ms)   SELECT * FROM "posts"
Comment Load (0.2ms)   SELECT "comments.*" FROM "comments" 
                       WHERE ("comments".post_id IN (1,2,3,4)) 
                       ORDER BY created_at asc) 

It is taking a shortcut because it pulls all of the comments at once, but it's still not a join (which is what all the documentation seems to say). 正在采取一种捷径,因为它会立即提取所有注释,但它仍然不是连接(这是所有文档似乎都说的)。 The only way I can get a join is to use :joins instead of :include : 我可以获得连接的唯一方法是使用:joins而不是:include

Post.all(:joins => :comments)

And the logs show: 日志显示:

Post Load (6.0ms)  SELECT "posts".* FROM "posts" 
                   INNER JOIN "comments" ON "posts".id = "comments".post_id

Am I missing something? 我错过了什么吗? I have an app with half a dozen associations and on one screen I display data from all of them. 我有一个有六个关联的应用程序,在一个屏幕上我显示所有这些数据。 Seems like it would be better to have one join-ed query instead of 6 individuals. 似乎最好有一个加入查询而不是6个人。 I know that performance-wise it's not always better to do a join rather than individual queries (in fact if you're going by time spent, it looks like the two individual queries above are faster than the join), but after all the docs I've been reading I'm surprised to see :include not working as advertised. 我知道在性能方面,进行连接而不是单个查询并不总是更好(事实上,如果你花费时间,看起来上面的两个单独的查询比连接更快),但是在所有文档之后我一直在读,我很惊讶地看到:include不按宣传方式工作。

Maybe Rails is cognizant of the performance issue and doesn't join except in certain cases? 也许Rails 认识的性能问题,并除非在某些情况下,不加入呢?


解决方案:

参考一: https://en.stackoom.com/question/54Q8
参考二: https://stackoom.com/question/54Q8
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章