加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

ruby-on-rails – Rails / Postgres:列必须出现在GROUP BY子句

发布时间:2020-12-17 03:01:06 所属栏目:百科 来源:网络整理
导读:我有一个将用户加入帖子的范围,以便只获得具有可见帖子的用户.这适用于 MySQL,但PG更严格,并抛出错误. 用户模型: belongs_to :accountscope :have_posts,joins(:posts).where('posts.visible = true').group('users.id') 控制器: @account.users.have_post
我有一个将用户加入帖子的范围,以便只获得具有可见帖子的用户.这适用于 MySQL,但PG更严格,并抛出错误.

用户模型:

belongs_to :account

scope :have_posts,joins(:posts).where('posts.visible => true').group('users.id')

控制器:

@account.users.have_posts.each do |user|
  # do stuff
end

错误:

(PGError: ERROR: column “users.account_id” must appear in the GROUP BY clause or be used in an aggregate function: SELECT “users”.* FROM “users” INNER JOIN “posts” ON “posts”.”user_id” = “users”.”id” WHERE (“users”.account_id = 1) AND (recommendations.approved = true) GROUP BY users.id)

它抱怨来自@ account.users的“users.account_id”(因为我显然不希望数据库中的所有用户).

知道怎么解决?

解决方法

问题是GROUP BY子句.如果使用此选项,则无法选择任何非聚合字段,因此SELECT“users”.* […]不起作用.来自Postgres文档:

In general,if a table is grouped,columns that are not used in the
grouping cannot be referenced except in aggregate expressions.

这样的东西可能有用,虽然凌乱:

scope :have_posts,joins('inner join (select user_id from posts where visible = true group by user_id) users_with_posts on users_with_posts.user_id=users.id')

一种替代方案是使用MAX或MIN等聚合函数指定每个选定的字段,但这可能会使范围更长,功能更少.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读