查询输出模型中每个字段的唯一记录数?
给定一个这样的模型:
Contact (id, user_id, xxx, xxxxxxx)
我想要一个查询来输出联系人模型中唯一的 user_id 记录的数量?关于如何写这个有什么想法吗?
谢谢
Given a Model like:
Contact (id, user_id, xxx, xxxxxxx)
I would like to have a query that outputs that # of unique user_id records in the Contact model? Any thoughts on how to write this?
Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
在 SQL 中执行此操作有多种方法,但如果您想尽可能地尝试保持在 ActiveRecord 提供的 ORM 范围内,我认为以下是您将获得的最接近的方法:
@user_ids
然后将是从联系人表中的记录引用的所有用户 ID 的数组。如果您想知道有多少个,可以拨打@user_ids.count
。更新:另一种方法可以提供更多信息,无需实例化每个对象并避免编写 SQL,如下所示:
如您所见,响应是一个以用户 id 作为键的哈希值以及每个用户的数量作为值。您可以使用另一个
.count
获取唯一用户 ID 的数量:There are several ways of doing this in SQL, but if you want to try to keep within the ORM provided by ActiveRecord as much as possible I think the following is the closest you are going to get:
@user_ids
will then be an array of all the user ids referenced from records in the contact table. If you want to know how many there are you can just call@user_ids.count
.Update: Another way of doing this that provides even more information without the overhead of instantiating each object and avoids writing SQL is as follows:
As you can see, the response is a hash with the user ids as keys and the quantity for each user as the value. You can get the number of unique user ids with another
.count
:以下是一些替代方法:
Here are some alternative ways to do it: