使用活动记录进行计数/分组?
我有一个包含以下信息的表:
id | user_id | points
--------------------------
1 | 12 | 48
2 | 15 | 36
3 | 18 | 22
4 | 12 | 28
5 | 15 | 59
6 | 12 | 31
etc.
我想要的是前 10 个(数组),每个 user_id 包含最多条目(顺序从高到低)。 因此,使用上面的表,我需要以下数组作为回报:
- 12 => 3 行
- 15 => 2 行
- 18 => 1 行
- 等。
如何使用活动记录查询方法通过 CodeIgniter 执行此操作?这可以通过 COUNT 和 GROUP BY user_id 来完成吗?
I have a table with the following info:
id | user_id | points
--------------------------
1 | 12 | 48
2 | 15 | 36
3 | 18 | 22
4 | 12 | 28
5 | 15 | 59
6 | 12 | 31
etc.
What I want is a top 10 (array) with most entries per user_id (order high to low).
So using the table above I need the following array in return:
- 12 => 3 rows
- 15 => 2 rows
- 18 => 1 row
- etc.
How can I do this with CodeIgniter using the active record query method? Can this be done with COUNT and GROUP BY user_id?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
我相信您会想要这样的结果:
这将产生类似 UPDATE: 的结果
,正如一些人在评论中指出的那样,原始查询是对 user_ids 求和而不是对它们进行计数。我已更新活动记录查询来纠正此问题。
I believe you'll want something like this:
This will produce a result like
UPDATE: As some pointed out in the comments the original query was summing the user_ids rather than counting them. I've updated the active record query to correct this.
虽然这是一个迟到的答案,但我想说这会对你有所帮助......
Although it is a late answer, I would say this will help you...
我认为你应该用 FOUND_ROWS() 来计算结果和 SQL_CALC_FOUND_ROWS。您将需要两个查询:
select
、group_by
等。您将添加一个加号选择:SQL_CALC_FOUND_ROWS user_id
。在此查询之后运行查询:SELECT FOUND_ROWS()
。这将返回所需的数字。I think you should count the results with FOUND_ROWS() and SQL_CALC_FOUND_ROWS. You'll need two queries:
select
,group_by
, etc. You'll add a plus select:SQL_CALC_FOUND_ROWS user_id
. After this query run a query:SELECT FOUND_ROWS()
. This will return the desired number.此代码对日期范围内的行进行计数:
控制器:
模型:
其中“arvdate”和“dptrdate”是数据库上的两个日期,“reservation”是表名称。
View:
此代码用于返回行数。
要返回表数据,然后使用
This code counts rows with date range:
Controller:
Model:
where 'arvdate' and 'dptrdate' are two dates on database and 'reservation' is the table name.
View:
This code is to return number of rows.
To return table data, then use