mysql - 如何将列中的多个值与其他列合并,该列也有多个用逗号分隔的值
问题描述
column1 | column2 | Result
32,33 | A,B | A32,A33,B32,B33
我在上面给出了一个示例,其中我有两列,其中有多个值,用逗号分隔,我想合并前两列并希望得到结果列中所示的结果。
解决方案
在 MySQL 8.0 上,您可以首先根据逗号分隔值拆分列 -
with recursive col1 as (select 1 id, '32,33' as column1
union all
select 2, '34,35'),
rec_col1 as (select id, column1 as remain, substring_index( column1, ',', 1 ) as column1
from col1
union all
select id, substring( remain, char_length( column1 )+2 ),substring_index( substring( remain, char_length( column1 ) +2 ), ',', 1 )
from rec_col1
where char_length( remain ) > char_length( column1 )
结果
id column1
1 32
1 33
2 34
2 35
同样,第二列 -
with recursive col2 as (select 1 id, 'A,B' as column2
union all
select 2, 'C,D'),
rec_col2 as (select id, column2 as remain, substring_index( column2, ',', 1 ) as column2
from col2
union all
select id, substring( remain, char_length( column2 )+2 ),substring_index( substring( remain, char_length( column2 ) +2 ), ',', 1 )
from rec_col2
where char_length( remain ) > char_length( column2 ))
select id, column2 from rec_col2
order by id;
结果
id column2
1 A
1 B
2 C
2 D
拆分两列后,您可以根据 id 加入它们 -
select concat(c2.column2, c1.column1) result_rows
from rec_col1 c1
join rec_col2 c2 on c1.id = c2.id
结果
result_rows
A32
B32
C34
D34
A33
B33
C35
D35
最后你可以使用 GROUP_CONCAT 来组合它们——
select group_concat(c2.column2, c1.column1 order by c2.column2, c1.column1) result
from rec_col1 c1
join rec_col2 c2 on c1.id = c2.id
group by c2.id
result
A32,A33,B32,B33
C34,C35,D34,D35
推荐阅读
- node.js - 无法使用 Nodejs 连接 Mongodb 数据库
- aws-lambda - 如何并行调用阶跃函数?
- python - 芹菜工人错误:self.buffer = mmap.mmap(self.fd,self.size)FileNotFoundError:[Errno 2]没有这样的文件或目录
- python - 如何在不更改其他格式/样式的情况下更改 Excel 单元格的颜色?
- wso2 - 如何将用户从 SQL 数据库同步到 WSO2 身份服务器
- java - 如何将 if-else 转换为 Java8 可选
- javascript - 生产模式下的 Angular 项目错误:SyntaxError: Unexpected token { in JSON at position 65
- shell - Shell循环遍历特定目录中的所有文件
- android - html中css变换的android版本是什么
- authentication - 使用 Keycloak 作为 Oauth 2.0 IdP (Mercado Libre) 的代理