我有一个带有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
有没有更好的解决方案?
解决方法
这是预期的行为.
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