简体   繁体   中英

Transform set of data into a single column

Lets say I have this set of integers enclosed in the parenthesis (1,2,3,4,5).

Data I have:

(1,2,3,4,5)

And I would want them to be in a single column.

Expected Output:

 column 
--------
      1
      2
      3
      4
      5
(5 rows)

How can I do this? I've tried using array then unnest but with no luck. I know I'm doing something wrong. I need this to optimize a query that is using a large IN statement, I want to put it in a temp table then join it on the main table.

You can convert the string to an array, then do the unnest:

select *
from unnest(translate('(1,2,3,4,5)', '()', '{}')::int[]);

The translate() call converts '(1,2,3,4,5)' to '{1,2,3,4,5}' which is the string representation of an array. That string is then cast to an array using ::int[] .

You don't need a temp table, you can directly join to the result of the unnest.

select *
from some_table t 
  join unnest(translate('(1,2,3,4,5)', '()', '{}')::int[]) as l(id) 
    on t.id = l.id;

Another option is to simply use that array in a where condition:

select *
from some_table t
where t.id = any (translate('(1,2,3,4,5)', '()', '{}')::int[]);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM