String 带$delimiter的postgres加入列表
从这些表格中:String 带$delimiter的postgres加入列表,string,postgresql,join,delimiter,String,Postgresql,Join,Delimiter,从这些表格中: select group, ids from some.groups_and_ids; 结果: group | group_ids ---+---- winners | 1$4 losers | 4 others | 2$3$4 以及: 您将如何返回类似以下内容的内容: winners | bob, norbert losers | norbert others | robert, dingus, norbert 是否可以重新设计您的数据
select group, ids
from some.groups_and_ids;
结果:
group | group_ids
---+----
winners | 1$4
losers | 4
others | 2$3$4
以及:
您将如何返回类似以下内容的内容:
winners | bob, norbert
losers | norbert
others | robert, dingus, norbert
是否可以重新设计您的数据库?将所有组ID放在一列中会让生活变得艰难。如果你的桌子是空的
group | group_id
winners | 1
winners | 4
losers | 4
等等。这将是非常容易的。事实上,下面的查询就可以了,尽管我犹豫是否发布它,因为它会鼓励糟糕的数据库设计(IMHO)
p、 我冒昧地重命名了一些栏目,因为它们是保留字。你可以逃避它们,但为什么要让自己的生活变得困难呢
select group_name,array_to_string(array_agg(username),', ') -- array aggregation and make it into a string
from
(
select group_name,theids,username
from ids_and_names
inner join
(select group_name,unnest(string_to_array(group_ids,'$')) as theids -- unnest a string_to_array to get rows
from groups_and_ids) i
on i.theids = cast(id as text)) a
group by group_name
第一部分通过在groups\u和\u id
表上创建一个适当的视图来规范您的断表设计。然后,实际查询将ids_和_names
表连接到组的规范化版本,并再次聚合名称
注:我将group
重命名为group\u name
,因为group
是保留关键字
SQLFiddle:首先不应该将分隔值存储在单个列中。如果你规范化你的数据模型会更好。这个答案比我的答案更清晰——使用“with”可以让查询更容易理解,将数组放入“with”可以让一切变得更清晰。这也使得表格设计中的缺陷显而易见!您将如何对返回的名称进行排序?:)我指的是那些名字string@user3486527:这在我的编辑中:
string\u agg(p.name,,'order by p.name)
select group_name,array_to_string(array_agg(username),', ') -- array aggregation and make it into a string
from
(
select group_name,theids,username
from ids_and_names
inner join
(select group_name,unnest(string_to_array(group_ids,'$')) as theids -- unnest a string_to_array to get rows
from groups_and_ids) i
on i.theids = cast(id as text)) a
group by group_name
with normalized (group_name, id) as (
select group_name, unnest(string_to_array(group_ids,'$')::int[])
from groups_and_ids
)
select n.group_name, string_agg(p.name,',' order by p.name)
from normalized n
join ids_and_names p on p.id = n.id
group by n.group_name;