使用 STRING_AGG 函数时子查询返回多行

More than one row returned by a subquery when using STRING_AGG function

我在 PostgreSQL 中尝试执行 SELECT 查询时遇到错误SQL 11

select (
    SELECT STRING_AGG(u.first_name::text, ', ') 
    FROM game_authors AS gat 
    LEFT JOIN users AS u ON u.id = gat.user_id 
    WHERE gat.game_id = g.id AND gat.lang = 'uk' 
    GROUP BY gat.id ORDER BY gat.id ASC
) AS authors_string 
from "games" as "g" 
where "g"."status" != 10 
order by "g"."id" desc limit 10 offset 0

和 authors_string 应该作为字符串值获取。它抛出一个错误

ERROR: more than one row returned by a subquery used as an expression

我想这是因为子查询中的 GROUP BY 造成的,可以用 row_to_json 函数处理,但不知道我应该把它放在表达式中的什么地方。 ORDER BY 不适用于 GROUP BY 表达式,因为 SELECT.

中存在聚合函数

SQL版本

PostgreSQL 11.8 (Ubuntu 11.8-1.pgdg18.04+1) on x86_64-pc-linux-gnu, compiled by gcc (Ubuntu 7.5.0-3ubuntu1~18.04) 7.5.0, 64-bit

我认为您只想删除子查询中的 group by 子句:

select (
    select string_agg(u.first_name::text, ', ' order by gat.id asc) 
    from game_authors as gat 
    left join users as u on u.id = gat.user_id 
    where gat.game_id = g.id and gat.lang = 'uk' 
) as authors_string 
from games as g 
where g.status <> 10 
order by g.id desc 
limit 10

不要使用标量 sub-select,而是使用派生的 table。通常情况下,这样效率更高:

select a.authors_string 
from games as g 
  join (
    SELECT gat.game_id, STRING_AGG(u.first_name::text, ', ' order by gat.id)  as authors
    FROM game_authors AS gat 
      LEFT JOIN users AS u ON u.id = gat.user_id 
    WHERE AND gat.lang = 'uk' 
    GROUP BY gat.id 
  ) a ON a.game_id = g.id
where g.status <> 10 
order by g.id desc 
limit 10 offset 0

虽然left join似乎没用