发表has_many
条评论。评论belongs_to
发表评论。我试图找回最近评论的列表,但每个帖子只有一个。
以下SQL返回PostgreSQL中设置的正确注释结果:
SELECT
comments.*
FROM
(SELECT
post_id, MAX(created_at) AS created_at
FROM
comments
GROUP BY
post_id) AS latest_comments
INNER JOIN
comments
ON
comments.post_id = latest_comments.post_id AND
comments.created_at = latest_comments.created_at
如何定义查询以使用ActiveRecord返回相同的结果集?
答案 0 :(得分:1)
这并不等同于您的SQL,但我相信也应该有效:
Comment.where(
created_at: Comment.select('max(created_at)').group(:post_id)
)
# Comment Load (6.9ms) SELECT "comments".* FROM "comments" WHERE "comments"."created_at" IN (
# SELECT max(created_at) FROM "comments" GROUP BY "comments"."post_id"
# ) LIMIT $1 [["LIMIT", 11]]