Explode/Split根据列值将一行分成多行
Explode/Split one row into multiple rows based on column value
我有一个 table 我需要分解和拆分 - 根据 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
我试图交叉连接到同一个 table 但它没有产生这个输出
此外,据我所知,MariaDB 没有原生的“split_part”函数,我正在努力避免为此目的创建程序。
数据库: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));
我建议您修复数据模型,这样您就不会在单个字符串中存储多个值。
Here 是一个 db<>fiddle.
我有一个 table 我需要分解和拆分 - 根据 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
我试图交叉连接到同一个 table 但它没有产生这个输出
此外,据我所知,MariaDB 没有原生的“split_part”函数,我正在努力避免为此目的创建程序。
数据库:MariaDB 10.2
这很痛苦,但你可以构建一个数字列表,然后使用 substring_index()
.
然后您需要从字符串中删除您似乎不需要的其他字符:
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));
我建议您修复数据模型,这样您就不会在单个字符串中存储多个值。
Here 是一个 db<>fiddle.