[英]Rails 3 and Active Record Query - 2 informations in one query
I am trying to find a way, how to get the statement of data in database (this is simple) and how to get the count of items. 我试图找到一种方法,如何获取数据库中的数据语句(这很简单)以及如何获取项目计数。 I am struggling with this problem a whole day and have not an idea, how to solve it...
我整天都在努力解决这个问题,却不知道如何解决...
I have following structure: 我有以下结构:
ID: first: second: name:
1 2 5 Emma
2 2 5 Emma
3 3 4 Luis
4 5 2 Mark
I want to get following statement: 我想得到以下声明:
Emma
Luis
Mark
This is easy. 这很容易。 But to each of the name I would like to add the information about the count of rows in database, for this example it would be like:
但是,对于每个名称,我想添加有关数据库中行数的信息,对于此示例,它将是:
Emma 2
Luis 1
Mark 1
The first statement is possible to get with a query Model.where("some condition") , but I don't know, how to get the second statement... 第一条语句可以通过查询Model.where(“ some condition”)获得 ,但我不知道如何获得第二条语句...
Thank you in advance 先感谢您
您可以使用诸如Model.where("some condition").count & you
将得到它
Model.group(:name).count
这应该返回
{"Emma" => 2, "Luis" => 1, "Mark" => 1}
You can use: 您可以使用:
User.select('users.*, count(*) AS times').group(:name)
In that case you have all attributes of User model + times which is count of name attribute. 在这种情况下,您具有“用户模型” +“时间”的所有属性,即“名称”属性的计数。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.