PostgreSQL unnest() with element number

后端 未结 5 1921
情话喂你
情话喂你 2020-11-21 15:21

When I have a column with separated values, I can use the unnest() function:

myTable
id | elements
---+------------
1  |ab,cd,efg,hi
2  |jk,lm,n         


        
5条回答
  •  梦如初夏
    2020-11-21 15:59

    Use Subscript Generating Functions.
    http://www.postgresql.org/docs/current/static/functions-srf.html#FUNCTIONS-SRF-SUBSCRIPTS

    For example:

    SELECT 
      id
      , elements[i] AS elem
      , i AS nr
    FROM
      ( SELECT 
          id
          , elements
          , generate_subscripts(elements, 1) AS i
        FROM
          ( SELECT
              id
              , string_to_array(elements, ',') AS elements
            FROM
              myTable
          ) AS foo
      ) bar
    ;
    

    More simply:

    SELECT
      id
      , unnest(elements) AS elem
      , generate_subscripts(elements, 1) AS nr
    FROM
      ( SELECT
          id
          , string_to_array(elements, ',') AS elements
        FROM
          myTable
      ) AS foo
    ;
    

提交回复
热议问题