Rails 3.1 with PostgreSQL: GROUP BY must be used in an aggregate function

前端 未结 4 1818
再見小時候
再見小時候 2020-12-15 12:30

I am trying to load the latest 10 Arts grouped by the user_id and ordered by created_at. This works fine with SqlLite and MySQL, but gives an error on my new PostgreSQL data

4条回答
  •  夕颜
    夕颜 (楼主)
    2020-12-15 12:37

    You need to select the specific columns you need

    Art.select(:user_id).group(:user_id).limit(10)

    It will raise error when you try to select title in the query, for example

    Art.select(:user_id, :title).group(:user_id).limit(10)

    column "arts.title" must appear in the GROUP BY clause or be used in an aggregate function

    That is because when you try to group by user_id, the query has no idea how to handle the title in the group, because the group contains several titles.

    so the exception already mention you need to appear in group by

    Art.select(:user_id, :title).group(:user_id, :title).limit(10)

    or be used in an aggregate function

    Art.select("user_id, array_agg(title) as titles").group(:user_id).limit(10)

提交回复
热议问题