Rails:include vs.:joins [英] Rails :include vs. :joins

查看:98
本文介绍了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...

因此,你知道你要使用的关联记录的福音是使用:include ,因为你会得到一个连接,避免一堆额外的查询:

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:

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) 

/ em>采取快捷方式,因为它一次拉所有的评论,但它仍然不是一个连接(这是所有的文档似乎说)。我可以得到加入的唯一方法是使用:joins 而不是:include

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:

Post.all(:joins => :comments)

并且日志显示:

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


$ b b

我错过了什么?我有一个应用程序与六个关联,在一个屏幕上,我显示所有的数据。似乎更好的是有一个联合查询,而不是6个人。我知道,性能方面,并不总是更好的做一个联接而不是个别的查询(事实上,如果你的时间花费,看起来像上面的两个单独的查询比连接快),但在所有的文档我一直在阅读我很惊讶看到:include 不能正常工作。

也许Rails

Maybe Rails is cognizant of the performance issue and doesn't join except in certain cases?

推荐答案

看来, :include 功能已更改Rails 2.1。 Rails用于在所有情况下执行连接,但出于性能原因,它在某些情况下更改为使用多个查询。 此博文 by Fabio Akita有一些关于改变的好的信息(见标题为优化的急加载部分)。

It appears that the :include functionality was changed with Rails 2.1. Rails used to do the join in all cases, but for performance reasons it was changed to use multiple queries in some circumstances. This blog post by Fabio Akita has some good information on the change (see the section entitled "Optimized Eager Loading").

这篇关于Rails:include vs.:joins的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆