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
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章