根据列值将一行分解/拆分为多行



我有一个表需要分解和拆分-根据MariaDB:中的app_permissions列值从一行生成多行

[email]        | [app_permissions]
john@p.ai      | {draft49:CAN_ACCESS_APP;CAN_VIEW_FINANCIAL_DATA}; {com.cc.worker:CAN_ACCESS_APP;CAN_VIEW_FINANCIAL_DATA} 

这是预期的查询结果:

[email]        | [app_permissions]
john@p.ai      | draft49:CAN_ACCESS_APP
john@p.ai      | draft49:CAN_VIEW_FINANCIAL_DATA
john@p.ai      | com.cc.worker:CAN_ACCESS_APP
john@p.ai      | com.cc.CAN_VIEW_FINANCIAL_DATA

我试图交叉连接到同一个表,但它没有产生这个输出

此外,不存在本地";split_part";据我所知,我正在努力避免为此目的创建过程。

DB:MariaDB 10.2

这相当痛苦,但您可以构建一个数字列表,然后使用substring_index()提取分号之间的第n个子字符串。

然后,您需要从字符串中删除您似乎不想要的其他字符:

select t.email,
replace(replace(replace(substring_index(substring_index(t.app_permissions, ';', n.n), ';', -1), '}', ''), '{', ''), ' ', '') as permission
from t join
(select 1 as n union all select 2 as n union all select 3 as n union all select 4 as n union all select 5) n
on t.app_permissions like concat('%', repeat(';%', n - 1));

我建议您修复数据模型,这样就不会在一个字符串中存储多个值。

这里有一个db<gt;不停摆弄

最新更新