SQL Error [21000]: ERROR: more than one row returned by a subquery used as an expression

SQL Error [21000]: ERROR: more than one row returned by a subquery used as an expression

我有三个 table 如下:

视频Table 身份证名称 1 你好 2世界 3 个新

标签table

id   name
1    tag1
2    tag2
3    tag3

videoTag table

videoId    tagId
1          1
2          1
1          2
2          3

我想要的是:

name       tags
hello      tag1, tag2
world      tag1, tag3

所以,我写了下面的查询。

select
        string_agg(name, ', ')
    from
        tag t
    join "videoTag" vt on
        vt."tagId" = t."id"
    group by
        vt."videoId"
    order by
        vt."videoId" 

结果如下

tags
tag1, tag2
tag1, tag3

我有完整的查询:

with videoDetails("name",
"tags") as (
select
    v."name" as "name",
    (
    select
        string_agg(name, ', ')
    from
        tag t
    join "videoTag" vt on
        vt."tagId" = t."id"
    group by
        vt."videoId"
    order by
        vt."videoId" 
) as " tag"
from
    video v
join "videoTag" vt on
    vt."videoId" = v.id
join tag t on
    t.id = vt."tagId"
order by
    vt."videoId" 
    )
select
    *
from
    videoDetails;

因此,我收到以下错误: SQL错误[21000]:错误:用作表达式的子查询返回多于一行

子 select 不需要(并且 return 多于一行,因此会出现错误)。我想你可以这样简化:

select
    v."name" as "name",
    string_agg(t."name", ', ' order by vt."videoId") as "tags"
from
    video v
join "videoTag" vt on
    vt."videoId" = v.id
join tag t on
    t.id = vt."tagId"
group by v."name";