gpt4 book ai didi

postgresql - 如何将多个行值展平为 postgres 中的连接字符串?

转载 作者:行者123 更新时间:2023-11-29 13:38:42 25 4
gpt4 key购买 nike

我有一组简单的三张表。 2 个“源”表和一个允许一对多关系的“连接”表。

我有这个问题:

          select data.mph1.data ->> 'name' as name, data.mph1.data ->> 'tags' as Tags, 
data.mph2.data ->> 'School' as school from data.mph1
join data.mph1tomph2 on data.mph1tomph2.mph1 = data.mph1.id
join data.mph2 on data.mph2.id = data.mph1tomph2.mph2

输出显示为:

            Name             Tags                                School
"Steve Jones" "["tag1", "tag2"]" "UMass"
"Steve Jones" "["tag1", "tag2"]" "Harvard"
"Gary Summers" "["java", "postgres", "flutter"]" "Yale"
"Gary Summers" "["java", "postgres", "flutter"]" "Harvard"
"Gary Summers" "["java", "postgres", "flutter"]" "UMass"

我要找的是

            Name             Tags                               School
"Steve Jones" "["tag1", "tag2"]" "UMass", "Harvard"
"Gary Summers" "["java", "postgres", "flutter"]" "Yale, Harvard, UMass"

如何在单个查询中获得此结果?可能吗?

最佳答案

使用聚合函数string_agg()

select 
data.mph1.data ->> 'name' as name,
data.mph1.data ->> 'tags' as tags,
string_agg(data.mph2.data ->> 'School', ', ') as school
from data.mph1
join data.mph1tomph2 on data.mph1tomph2.mph1 = data.mph1.id
join data.mph2 on data.mph2.id = data.mph1tomph2.mph2
group by data.mph1.id -- if id is a primary key
-- group by 1, 2 -- otherwise

关于postgresql - 如何将多个行值展平为 postgres 中的连接字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58699247/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com