PostgreSQL json_agg,并尝试分组和排序(列必须出现在 GROUP BY 中)

nac*_*son 2 postgresql

我已经阅读了一些关于此错误的 stackoverflow,但我仍然不明白。

-- Returns full JSON document of a user, and all their user_files.
with user_files_json as (
    select user_id,
           json_agg(
             json_build_object(
               'user_file_id', user_file_id,
               's3_key', s3_key,
               'settings', series_settings
             )
           ) as user_files
      from user_files
     where user_id = :user_id
  group by user_id
  order by user_file_id asc
)
select json_build_object(
         'user_id', user_id,
         'user_name', user_name,
         'job_type_name', job_type_name,
         'user_files', user_files
       )
  from user_files_json
  join users using(user_id)
  join job_type using(job_type_id);
Run Code Online (Sandbox Code Playgroud)

我希望文件按其 user_file_id 顺序列出。就这样。如果我取出order by工作,但文件以错误的顺序出现。

但我收到一条错误消息:

column "user_files.user_file_id" must appear in the GROUP BY clause or be used in an aggregate function
Run Code Online (Sandbox Code Playgroud)

作为一个人类,我告诉 postgresql 对我来说非常有意义,但是有人可以向我解释我做错了什么以及如何解决它吗?

Sam*_*nen 9

因此,您希望按 对 JSON 对象进行排序user_file_id。您必须首先创建 JSON 对象,然后对它们进行分组和聚合,因为 PostgreSQL 只返回聚合,user_id并且不能根据聚合内部的内容对这些对象进行排序,只能对结果集中的内容进行排序。

select user_id,
       json_agg(obj) as user_files
  from (
    select user_id, json_build_object(
           'user_file_id', user_file_id,
           's3_key', s3_key,
           'settings', series_settings
      order by user_file_id asc
         ) as obj
  from user_files
 where user_id = :user_id) tmp
group by user_id
Run Code Online (Sandbox Code Playgroud)