创建一个从字符串数组 [英] Create string from array

查看:150
本文介绍了创建一个从字符串数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在PostgreSQL里,一个表,包括:

I have a table in PostgreSQL that contains:

id   name   arrayofparents
1     First
2     Second      {1}
3     Second_Sec  {1,2}
4     Third       {1,2,3}
5     Second_A    {1}
6     Other
7     Trash       {6}

arrayofparents 的类型为整数[] 它包含了父母的列表记录了与正确的那一行订单。

arrayofparents is of type integer[] it contains a list of the parents records for that row with the correct order.

ID = 4 家长:首先然后然后 Second_sec

我如何编写一个查询,对于任何给定的ID就会产生它的父母名字的字符串?

How do I write a query that for any given id it will generate a string of it's parents name?

例如:

ID = 3 第一 - >第二个

ID = 4 第一 - >二线> Second_sec

ID = 7 其他

编辑:
如果可能的话我preFER请求ID 名称总会出现。
ID = 3 第一 - >二线> Second_sec

ID = 4 第一 - >二线> Second_sec->三

ID = 7 其他 - >删除邮件

ID = 6 其他

推荐答案

您可以将喜欢generate_subscripts和阵列muliple操作得到的结果:

you can combine muliple operations like generate_subscripts and array to get the result:

with mtab as (
      SELECT id, name, array_append(arrayofparents,id) as arrayofparents,
      generate_subscripts(array_append(arrayofparents, id), 1) AS p_id FROM tab where id=2
)
select distinct array_to_string(
  array(
    select tab.name from tab join mtab t on tab.id=t.arrayofparents[t.p_id]
  ), '->'
) ;

活生生的例子Sqlfiddle

或使用外连接的任何组合:

or use outer join combined with any:

SELECT coalesce(string_agg(p.name, '->') || '->' || t.name, t.name) AS parentnames
FROM tab AS t
  LEFT JOIN tab AS p ON p.id = ANY(t.arrayofparents)
 where t.id =7 
GROUP BY t.id, t.name

活生生的例子Sqlfiddle

这篇关于创建一个从字符串数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆