查询输出模型中每个字段的唯一记录数?

发布于 2024-11-06 01:42:16 字数 147 浏览 0 评论 0原文

给定一个这样的模型:

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

ヅ她的身影、若隐若现 2024-11-13 01:42:16

在 SQL 中执行此操作有多种方法,但如果您想尽可能地尝试保持在 ActiveRecord 提供的 ORM 范围内,我认为以下是您将获得的最接近的方法:

@user_ids = Contact.select('DISTINCT user_id').all

@user_ids然后将是从联系人表中的记录引用的所有用户 ID 的数组。如果您想知道有多少个,可以拨打@user_ids.count


更新:另一种方法可以提供更多信息,无需实例化每个对象并避免编写 SQL,如下所示:

Contact.group('user_id').count  #=> { 1 => 3, 2 => 4, 3 => 10 }

如您所见,响应是一个以用户 id 作为键的哈希值以及每个用户的数量作为值。您可以使用另一个 .count 获取唯一用户 ID 的数量:

Contact.group('user_id').count.count  #=> 3

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 = Contact.select('DISTINCT user_id').all

@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:

Contact.group('user_id').count  #=> { 1 => 3, 2 => 4, 3 => 10 }

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:

Contact.group('user_id').count.count  #=> 3
鹿港小镇 2024-11-13 01:42:16

以下是一些替代方法:

Contact.count('user_id', :distinct => true)
# SELECT COUNT(DISTINCT "contacts"."user_id") FROM "contacts"

Contact.count('DISTINCT user_id')
# SELECT COUNT(DISTINCT user_id) FROM "contacts"

Here are some alternative ways to do it:

Contact.count('user_id', :distinct => true)
# SELECT COUNT(DISTINCT "contacts"."user_id") FROM "contacts"

Contact.count('DISTINCT user_id')
# SELECT COUNT(DISTINCT user_id) FROM "contacts"
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文