我如何加入派生表?

sql语句是这样的:

select posts.id, posts.title from posts inner join (select distinct post_id,created_at from comments order by created_at DESC limit 5 ) as foo on posts.id=foo.post_id order by foo.created_at DESC; 

我想获得一个相当于上面的rails 3 sql语句。

我尝试的内容如下:

以下sql查询给出了类似的结果。

 select distinct post_id, created_at from comments order by created_at DESC limit 5 @temp = Comment.select('distinct(comments.post_id),created_at').order('created_at DESC').limit(5) 

我试图将这个派生的@temp表加入posts表来获取posts.title

我尝试了这个但失败了。

 @temp2 = @temp.joins('posts') 

那么,我如何使用派生的@temp表加入posts表?

  Table "public.posts" Column | Type | Modifiers -------------+------------------------+---------------------------------------------------- id | integer | not null default nextval('posts_id_seq'::regclass) title | character varying(100) | not null content | character varying(500) | not null created_at | date | updated_at | date | tags | character varying(55) | not null default '50'::character varying category_id | integer | not null default 1 Indexes: "posts_pkey" PRIMARY KEY, btree (id) 

评论

  Table "public.comments" Column | Type | Modifiers ------------+------------------------+------------------------------------------------------- id | integer | not null default nextval('comments_id_seq'::regclass) post_id | integer | not null name | character varying(255) | not null email | character varying(255) | not null content | character varying(500) | not null created_at | date | updated_at | date | Indexes: "comments_pkey" PRIMARY KEY, btree (id) 

posts model, has_many :comments ,comments model, belongs_to :post

问题作者需要在跳转到SQL之前阅读基本的Rails和activerecord用法。 需要了解Activerecord如何为您的数据建模以及如何使用它。 首先找出你想用通用语言做什么,然后看看如何使用现有的做法。

Rails不知道你的@temp表的结构。 它只有一个结果集,据我所知,AREL不会从结果集中构建逻辑。 它从模式构建,它为活动记录模型提供了它。

您无法从此数据构建视图,因此您唯一的选择是使用带有activerecord类的标准连接选项或执行自定义sql。

在Rails 3中,ActiveRecord关系代数非常先进,使查询变得非常简单。

Comment.order("#{Comment.table_name}.created_at desc').limit(5).joins(:posts).order("#{Post.table_name} created_at desc")