PostgreSQL unnest() with element number

后端 未结 5 1920
情话喂你
情话喂你 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

    unnest2() as exercise

    Older versions before pg v8.4 need a user-defined unnest(). We can adapt this old function to return elements with an index:

    CREATE FUNCTION unnest2(anyarray)
      RETURNS setof record  AS
    $BODY$
      SELECT $1[i], i
      FROM   generate_series(array_lower($1,1),
                             array_upper($1,1)) i;
    $BODY$ LANGUAGE sql IMMUTABLE;
    

提交回复
热议问题