首页 > 解决方案 > 在 PostgreSQL 中解析文本数据

问题描述

我有一个 PostgreSQL 数据库,一个有 2 个文本列的表,存储数据如下:

id|         col1              |                     col2                      |
------------------------------------------------------------------------------|
1 | value_1, value_2, value_3 | name_1(date_1), name_2(date_2), name_3(date_3)|
2 | value_4, value_5, value_6 | name_4(date_4), name_5(date_5), name_6(date_6)|

我需要像这样解析新表中的行:

id |  col1   |  col2  |  col3  |
1  | value_1 | name_1 | date_1 |
1  | value_2 | name_2 | date_2 |
...|   ...   |  ...   |  ...   |
2  | value_6 | name_6 | date_6 |

我该怎么做?

标签: postgresqlpostgresql-9.5

解决方案


分步演示:db<>fiddle

SELECT
    id,
    u_col1 as col1,
    col2_matches[1] as col2,                                     -- 5
    col2_matches[2] as col3
FROM 
    mytable,
    unnest(                                                      -- 3
        regexp_split_to_array(col1, ', '),                       -- 1
        regexp_split_to_array(col2, ', ')                        -- 2
    ) as u (u_col1, u_col2),
    regexp_matches(u_col2, '(.+)\((.+)\)') as col2_matches       -- 4
  1. 将第一列的数据拆分为数组
  2. 将第二列的数据拆分为表单数组{a(a), b(b), c(c)}
  3. 将所有数组元素转置为自己的记录
  4. 将表单元素拆分为表单a(b)数组{a,b}
  5. 显示所需的列。对于col2andcol3显示第 4 步中的第一个或第二个数组元素

推荐阅读