我有一个帖子模型has_many
条评论。每个帖子都有一个线程ID(但是没有名为Thread的模型)。
所以,如果我想计算这篇文章中的线程数,我会像
一样> post.comments.count(:thread, :distinct => true)
SELECT COUNT(DISTINCT "comments"."thread") FROM "comments" WHERE "comments"."post_id" = 3
这很好用。但是,如果我只想用一条评论计算线程数呢?
> post.comments.group(:thread).having('COUNT(*) == 1').count
SELECT COUNT(*) AS count_all, thread AS thread FROM "comments" WHERE "comments"."post_id" = 3 GROUP BY thread HAVING COUNT(*) == 1 ORDER BY id
所以我有一个OrderedHash而不是Integer。我必须做不必要的步骤
> post.comments.group(:thread).having('COUNT(*) == 1').count.count
有没有更好的解决方案?
答案 0 :(得分:15)
这是预期的行为。
post.comments.group(:thread).having('COUNT(*) == 1').count
这将返回一个散列,其中键是线程ID,值是计数。我相信只要你在rails中使用聚合函数进行组操作就是这种情况。您必须进行第二次计数才能获得第一个查询匹配的结果数。
我不确定Rails中会出现这种情况,但这是我认为你想要的SQL:
SELECT COUNT(*) FROM
SELECT COUNT(*) AS count_all, thread AS thread
FROM "comments"
WHERE "comments"."post_id" = 3
GROUP BY thread
HAVING COUNT(*) == 1
ORDER BY id