MySQL逗号分割字段的行列转换技巧
来源:互联网 发布:网络驱动错误代码10 编辑:程序博客网 时间:2024/06/05 22:44
文章转自:http://www.cnblogs.com/cenalulu/archive/2012/08/20/2647463.html
前言:
由于很多业务表因为历史原因或者性能原因,都使用了违反第一范式的设计模式。即同一个列中存储了多个属性值(具体结构见下表)。
这种模式下,应用常常需要将这个列依据分隔符进行分割,并得到列转行的结果。
表数据:
IDValue1tiny,small,big2small,medium3tiny,big期望得到结果:
IDValue1tiny1small1big2small2medium3tiny3big正文:
#需要处理的表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);
select a.ID,substring_index(substring_index(a.mSize,',',b.AutoIncreID),',',-1) from tbl_name ajoinincre_table bon 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个数值,一般能满足于大部分需求了。
改写后如下:
select a.ID,substring_index(substring_index(a.mSize,',',b.help_topic_id+1),',',-1) from tbl_name ajoinmysql.help_topic bon b.help_topic_id < (length(a.mSize) - length(replace(a.mSize,',',''))+1)order by a.ID;
0 0
- MySQL逗号分割字段的行列转换技巧
- MySQL逗号分割字段的行列转换技巧
- MySQL逗号分割字段的行列转换技巧
- MySQL逗号分割字段的行列转换技巧
- MySQL逗号分割字段的行列转换技巧
- MySQL逗号分割字段的行列转换技巧
- MySQL逗号分割字段的行列转换技巧
- MySQL逗号分割字段的行列转换技巧
- MySQL逗号分割字段的行列转换
- MySQL逗号分割字段的行列转换测试改进
- mysql——逗号分割字段情况
- 逗号分割的字段值拆分
- MySQL的行列转换
- mysql的行列转换
- oracle用逗号分隔符分割的字段,转换中文说明
- mysql 字段值逗号分割后sql匹配
- 关于MYSQL的行列转换
- 逗号分割符--字段中含逗号等情况的解析方法Java实现
- Hibernate注解使用方法总结
- 题目599 奋斗的小蜗牛
- php heredoc 与 nowdoc
- JavaSript模块化---AMD&&CMD
- 在乌班图系统下编译安卓系统整个模块,遇到的问题
- MySQL逗号分割字段的行列转换技巧
- Jsoup报HTTP error fetching URL. Status=403, URL=。。。
- mysql慢查询解决方法
- ubuntu系统中import h5py, ImportError: No module named h5py的解决方法
- android 判断应用前台还是后台
- java web学习之servlet
- 特别困的学生 (特困生)
- 爱卡汽车网某重要系统设计逻辑缺陷(成功绕过验证码限制)影响内部敏感信息
- POJ 3026 Borg Maze