将逗号分隔的数据库项目转换为隔离的行

时间:2016-10-12 18:35:36

标签: java postgresql

我有以下表数据..表名是类别

| ID             | Data                     | 
+----------------+--------------------------+
| 1              | Apple,Orance-........... | 
| 2              | Apple,Grapes-........... | 
| 3              | Juice,Apple,Cucumber-... |

有没有办法可以将上面的逗号分隔值转换为个别行的值,如下所示?

| ID          | SplitData
+-------------+-------------------
| 1           | Apple
| 2           | Orange
| 3           | Grapes
| 4           | Juice
| 5           | Cucumber

我使用postgres for db和Jersey来检索数据,

1 个答案:

答案 0 :(得分:1)

string_to_array()中使用unnest()

with a_table(id, data) as (
    values
        (1, 'Apple,Orance'),
        (2, 'Apple,Grapes'),
        (3, 'Juice,Apple,Cucumber')
)

select id, elem
from a_table,
lateral unnest(string_to_array(data, ',')) elem

 id |   elem   
----+----------
  1 | Apple
  1 | Orance
  2 | Apple
  2 | Grapes
  3 | Juice
  3 | Apple
  3 | Cucumber
(7 rows)

使用distinct获取不同的元素:

with a_table(id, data) as (
    values
        (1, 'Apple,Orance'),
        (2, 'Apple,Grapes'),
        (3, 'Juice,Apple,Cucumber')
)

select distinct on (elem) elem
from a_table,
lateral unnest(string_to_array(data, ',')) elem

   elem   
----------
 Apple
 Cucumber
 Grapes
 Juice
 Orance
(5 rows)