MYSQL字段内容逗号分割的行列转换技巧

MYSQL字段内容逗号分割的行列转换技巧

有的传统公司项目,或者历史原因造成的表结构部分字段设计不合理,例如字段内容使用逗号等分割的情况,这里针对这部分数据的查询的一个小技巧,避免逻辑代码查询数据后再对数据进行二次处理

原始数据:
ID Value 1 tiny,small,bi 2 small,medium 3 tiny,big

期望得到的结果:

ID Value 1 tiny 1 small 1 big 2 small 2 medium 3 tiny 3 big

1.建立测试表

1
2
3
4
5
6
7
8
9
10
11
#需要处理的表
create table tbl_name (ID int ,mSize varchar(100));
insert into tbl_name values (1,'tiny,small,big');
insert into tbl_name values (2,'small,medium');
insert into tbl_name values (3,'tiny,big');

#用于循环的自增表
create table incre_table (AutoIncreID int);
insert into incre_table values (1);
insert into incre_table values (2);
insert into incre_table values (3);

2.查询语句

1
2
3
4
5
6
7
8
SELECT
a.ID,
substring_index( substring_index( a.mSize, ',', b.AutoIncreID ), ',',- 1 )
FROM
tbl_name a
JOIN incre_table b ON b.AutoIncreID <= ( length( a.mSize ) - length( REPLACE ( a.mSize, ',', '' ) ) + 1 )
ORDER BY
a.ID;

原理分析:
这个join最基本原理是笛卡尔积。通过这个方式来实现循环。
以下是具体问题分析:
length(a.Size) - length(replace(a.mSize,’,’,’’))+1 表示了,按照逗号分割后,改列拥有的数值数量,下面简称n
join过程的伪代码:
根据ID进行循环
{
判断:i 是否 <= n
{
获取最靠近第 i 个逗号之前的数据, 即 substring_index(substring_index(a.mSize,’,’,b.ID),’,’,-1)
i = i +1
}
ID = ID +1
}

总结
这种方法的缺点在于,我们需要一个拥有连续数列的独立表(这里是incre_table)。并且连续数列的最大值一定要大于符合分割的值的个数。
例如有一行的mSize 有100个逗号分割的值,那么我们的incre_table 就需要有至少100个连续行。
当然,mysql内部也有现成的连续数列表可用。如mysql.help_topic: help_topic_id 共有504个数值,一般能满足于大部分需求了。
改写后如下:

1
2
3
4
5
6
7
8
SELECT
a.ID,
substring_index( substring_index( a.mSize, ',', b.help_topic_id + 1 ), ',',- 1 )
FROM
tbl_name a
JOIN mysql.help_topic b ON b.help_topic_id < ( length( a.mSize ) - length( REPLACE ( a.mSize, ',', '' ) ) + 1 )
ORDER BY
a.ID;

关注Github:1/2极客

关注博客:御前提笔小书童

关注公众号:开发者的花花世界


本作品采用知识共享署名 4.0 中国大陆许可协议进行许可,欢迎转载,但转载请注明来自御前提笔小书童,并保持转载后文章内容的完整。本人保留所有版权相关权利。

本文链接:https://royalscholar.cn/2019/07/31/MYSQL字段内容逗号分割的行列转换技巧/

# MySQL

评论

Your browser is out-of-date!

Update your browser to view this website correctly. Update my browser now

×