加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

ruby-on-rails – Rails ActiveRecord独特的属性计数大于出现次

发布时间:2020-12-17 02:27:52 所属栏目:百科 来源:网络整理
导读:我有一个表author_comments,其中包含字段author_name,comment和brand id. 我想得到记录的数量(计数),其中作者对于给定品牌具有超过N(2)条记录. 例如, author_comments author_name comment brandjoel "loves donuts" 1joel "loves cookies" 1joel "loves ora
我有一个表author_comments,其中包含字段author_name,comment和brand id.

我想得到记录的数量(计数),其中作者对于给定品牌具有超过N(2)条记录.

例如,

author_comments

author_name      comment                 brand

joel             "loves donuts"             1

joel             "loves cookies"            1

joel             "loves oranges"            1

fred             "likes bananas"            2

fred             "likes tacos"              2

fred             "likes chips"              2

joe              "thinks this is cool"      1

sally            "goes to school"           1

sally            "is smart"                 1

sally            "plays soccer"             1

在这种情况下,我的查询应该为品牌1返回2,为品牌2返回1.

我对这里表现最好的选项感兴趣,没有从db获取所有记录并在ruby中对它们进行排序,我可以这样做.我正在寻找使用活动记录结构或sql的最佳方法.

更新:
这是SQL:

SELECT author_name,COUNT(*) AS author_comments
FROM fan_comments
WHERE brand_id =269998788
GROUP BY author_name
HAVING author_comments > 2;

我应该做find_by_sql吗?

解决方法

您可以使用活动记录构造定义相同的查询:

FanComments.all(
  :select => 'author_name,count(*) as author_comments',:group => 'author_name',:having => 'author_comments > 2') # in rails 2

要么:

FanComments.
  select('author_name,count(*) as author_comments').
  group('author_name').
  having('author_comments > 2') # in rails 3

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读