可能重复:
Ruby on Rails: How can i join with a derived table?
员额表
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)
我正在尝试对此做一个等价的rails 3 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;
这是为了得到最近的评论-帖子(限制5)。这是一个复杂的sql查询。需要从posts表中选择posts.title,加入注释表。
发布于 2011-12-08 23:21:07
执行这样的查询的Rails3方法是find_by_sql
posts = Post.find_by_sql(%q{
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
})
如果您想要的话,可以使用joins
,但是,IMHO,这只会混淆一些事情:
Post.select('posts.id, posts.title').
joins('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('foo.created_at desc')
或者更复杂的事情,比如:
join_to = Comment.select('distinct post_id, created_at').
order('created_at desc').
limit(5).
to_sql
posts = Post.select('posts.id, posts.title').
joins("join (#{join_to}) as foo on posts.id = foo.post_id").
order('foo.created_at desc')
在SQL中,有些事情比AREL更容易、更清晰。存在find_by_sql
method是有原因的:
find_by_sql
为您提供了一种对数据库进行自定义调用和检索实例化对象的简单方法。
这类事情正是find_by_sql
的作用所在。您将不得不退出find_by_sql
以获得许多高级的SQL特性(例如CTE),并且没有理由害怕或避免它: ActiveRecord是一种工具,而不是一种教条的生活方式。find_by_sql
确实有缺点(比如不能很好地处理作用域),但是标准的AREL也有缺点(比如不很好地处理非平凡的SQL)。
https://stackoverflow.com/questions/8438451
复制相似问题