postgresql - 在 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 |
我该怎么做?
解决方案
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
- 将第一列的数据拆分为数组
- 将第二列的数据拆分为表单数组
{a(a), b(b), c(c)}
- 将所有数组元素转置为自己的记录
- 将表单元素拆分为表单
a(b)
数组{a,b}
- 显示所需的列。对于
col2
andcol3
显示第 4 步中的第一个或第二个数组元素
推荐阅读
- angular - 在 .pipe() 中使用 delay(2000) 时,.subscribe 不会被触发。(角度 Rxjs)
- vue.js - 我可以将默认端口从 8080 更改为 Vue 中的其他端口吗?
- php - Laravel:比较数据库中两列之间的日期不起作用
- redirect - 如何将ip重定向到子域
- spring - 我想获取一个数据库中的所有表并在jsp中显示
- r - lrtest(似然比检验)使用plgm包计数数据
- php - Composer 自动加载性能
- cordova - OneSignal 订阅用户?
- postgresql - 复杂匹配和加入 PostgreSQL
- c# - 剃刀视图的预编译