Create string from array

前端 未结 3 1458
离开以前
离开以前 2021-01-14 23:56

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          


        
3条回答
  •  再見小時候
    2021-01-15 00:51

    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]
      ), '->'
    ) ;
    

    live example 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
    

    live example Sqlfiddle

提交回复
热议问题