Rails 4中的嵌套SQL SELECT

时间:2016-03-27 18:40:37

标签: ruby-on-rails ruby-on-rails-4 rails-activerecord

我正在寻找一种在Rails中生成以下SQL的方法(使其成为范围),以便我可以使用scopes进一步链接它(例如Article.published.most_comments):< / p>

SELECT *, cs.count
FROM articles, (
  SELECT article_id, count(*)
  FROM comments
  GROUP BY comments.article_id
) cs
WHERE articles.id = cs.article_id
ORDER BY cs.count DESC;

我尝试了Article.joins(:comments).select('*').group('comments.article_id')的某些内容,但这并没有生成所需的SQL:

SELECT * FROM "articles"
INNER JOIN "comments" ON "comments"."article_id" = "articles"."id"
GROUP BY comments.article_id

(PSQL): PG::GroupingError: ERROR:  column "articles.id"
        must appear in the GROUP BY clause or be used in
        an aggregate function

并且似乎不是.from方法,我可以在其中指定嵌套的SQL SELECT。

1 个答案:

答案 0 :(得分:1)

实际上,有一个.from method

scope :most_comments, -> {
  Article.select('*, cs.count').from(
    'articles, (
      SELECT article_id, count(*)
      FROM comments
      GROUP BY comments.article_id
      ) cs'
    )
    .where('articles.id = cs.article_id')
    .order('cs.count DESC')
}

不确定这是否是最佳方式,但它有效......