最大的集团主动记录查询 [英] Maximum in group by active record query

查看:158
本文介绍了最大的集团主动记录查询的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个模型,它有两个属性(我只显示两成只需要这两列)

I have a Model which has two attributes (I am showing only two as only those two columns are needed)

为MyModel

place_id ------------------------ USER_ID

place_id ------------------------ user_id

1 ---------------------------------- 1

1 ---------------------------------- 1

1 ---------------------------------- 2

1 ---------------------------------- 2

1 ---------------------------------- 2

1 ---------------------------------- 2

3 ---------------------------------- 3

3 ---------------------------------- 3

3 ---------------------------------- 2

3 ---------------------------------- 2

3 ---------------------------------- 3

3 ---------------------------------- 3

3 ---------------------------------- 1

3 ---------------------------------- 1

我想在最大记录取出组。基本上我想获取哪些用户有一个像为place_id 1用户2具有最大的效果,并为地方3用户3具有最大的效果最大记录一个特定的地方。

I want to fetch group by maximum records. Basically I want to fetch for a particular place which user has maximum records like for for place_id 1 user 2 has maximum results and for place 3 user 3 has maximum results.

推荐答案

如果您指定一个地方首先,你可以这样做:

If you are specifying a place first you can do:

MyModel.where("place_id=?",place_id).
        group("place_id,user_id").order("count(user_id) DESC").first

如果你想获得的所有的最大值一次,然后通过你的结果集删除where子句和迭代,只取第一条记录为每个不同的place_id。或者,您可以添加一个独特的声明以上。像这样的事情?

If you want to get all the maximums at once, then remove the where clause and iterate through your result set, taking only the first record for each distinct place_id. Or you may be able to add a distinct to the statement above. Something like this?

MyModel.select("DISTINCT(place_id)").
        merge(MyModel.group("place_id,user_id").order("count(user_id) DESC"))

祝你好运!

这篇关于最大的集团主动记录查询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆