实例表:
postgres=# \d book
Table "public.book"
Column | Type | Modifiers
--------+-------------------+---------------------------------------------------
id | integer | not null default nextval('book_id_seq'::regclass)
name | character varying |
tag | character varying |
postgres=# select * from book; id | name | tag ----+------+---------- 1 | java | aa,bb,cc 2 | C++ | dd,ee(2 rows)需要的效果:
name | unnest
------+--------
java | aa
java | bb
java | cc
C++ | dd
C++ | ee
(5 rows)
方法1: unnest(数组,分隔符)
postgres=# select name,unnest(string_to_array(tag,',')) from book;
name | unnest
------+--------
java | aa
java | bb
java | cc
C++ | dd
C++ | ee
(5 rows)
postgres=# select string_to_array(tag,',') from book; string_to_array ----------------- {aa,bb,cc} {dd,ee}(2 rows)方法2:regexp_split_to_table(字符串,分隔符)
postgres=# select name,regexp_split_to_table(tag,',') from book;
name | regexp_split_to_table
------+-----------------------
java | aa
java | bb
java | cc
C++ | dd
C++ | ee
(5 rows)
另外,字符串变数组的方法:
postgres=# select name,string_to_array(tag,',') from book;
name | string_to_array
------+-----------------
java | {aa,bb,cc}
C++ | {dd,ee}
(2 rows)
postgres=# select name,regexp_split_to_array(tag,',') from book; name | regexp_split_to_array ------+----------------------- java | {aa,bb,cc} C++ | {dd,ee}(2 rows)