可能性の重複:
Ruby on Rails: How can i join with a derived table?これに相当するレール3のSQL文を誰でも投稿できますか?
ポストテーブル
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)
私が作るしようとしていますこれに相当する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.titleを選択する必要があります。物事を難読化でしょう
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
を使用することができ、::
'find_by_sql'の何が問題なのですか? –
私はfind_by_sqlの作品を知っていますが、私は複雑なSQLクエリのためのレール3 SQL文を探しています。 – shibly