简体   繁体   English

Rails Postgres GROUP所有列

[英]Rails Postgres GROUP all columns

You must GROUP BY all columns you are selecting by in Postgres or it will get mad at you. 您必须在Postgres中选择的所有列都按GROUP BY ,否则它会惹恼您。 Is there a simple/clean way to do this other than just listing all the columns? 除了列出所有列之外,是否有简单/干净的方法来执行此操作?

The best I've come up with is the following (intent is commented): 我想出的最好的是以下内容(意图已注释):

# The purpose of this query is to return a list of `User`s
# ordered by the number of `Account`s they have in descending order.

User.joins(:accounts)
    .group(User.full_column_names)
    .order('COUNT("accounts".*) DESC')

From user.rb : user.rb

def self.full_column_names
  column_names.collect {|name| "\"#{table_name}\".\"#{name}\"" }
end

One way to find the user with the most accounts: 查找拥有最多帐户的用户的一种方法:

user_id, number_of_accounts = Account.group(:user_id).count.max_by{ |key, value| value}
user_with_most_accounts = User.find(user_id)

Make it one query with: 使用以下命令进行查询:

user_with_most_accounts = User.find(Account.group(:user_id).count.max_by{ |key, value| value}[0])

Note : This finds only one user even if multiple users have the same number of accounts as the most count. 注意 :即使多个用户拥有最多数量的相同帐户数,也只能找到一个用户。

Enough time has passed where I have to say that unfortunately there is not a better solution for the specific question I was asking. 足够的时间过去了,我不得不说,不幸的是,对于我所问的具体问题,没有更好的解决方案。 Maybe Rails 5 will have something and I'll revisit this later. 也许Rails 5会有所帮助,我稍后会再讨论。 My basic solution in the question works for my usage and could be modified or used in another higher level method without much work to perform the grouping. 我在该问题中的基本解决方案适用于我的用法,无需进行大量工作即可进行分组就可以对其进行修改或用于其他更高级别的方法中。

This may also be solved in a update to the Postgres adapter. 这也可以通过更新Postgres适配器来解决。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM