mysql列转行的技巧实例分享

下面小编就为大家带来一篇mysql 列转行的技巧(分享)。小编觉得挺不错的,现在就分享给大家,也给大家做个参考。一起跟随小编过来看看吧

前言:

由于很多业务表因为历史原因或者性能原因,都使用了违反第一范式的mysql。即同一个列中存储了多个mysql值(具体结构见下表)。

这种模式下,应用常常需要将这个列依据分隔符进行分割,并得到列转行的结果。

表数据:

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

期望得到结果:

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

正文:

#需要处理的表  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 a  join  incre_table b  on b.AutoIncreID <p><span style="background-color: #ccffcc"><strong>原理分析:</strong></span></p><p>这个join最基本原理是笛卡尔积。通过这个方式来实现循环。</p><p><span style="background-color: #ccffcc"><strong>以下是具体问题分析:</strong></span></p><p>length(a.Size) - length(replace(a.mSize,',',''))+1  表示了,按照逗号分割后,改列拥有的数值数量,下面简称n</p><p><span style="color: #ff00ff"><strong>join过程的伪代码:</strong></span></p><p>根据ID进行循环</p><pre class="brush:js;toolbar:false">{  判断:i 是否 <p>获取最靠近第 i 个逗号之前的数据, 即 substring_index(substring_index(a.mSize,',',b.ID),',',-1)</p><pre class="brush:js;toolbar:false">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 a  join  mysql.help_topic b  on b.help_topic_id 

© 版权声明
THE END
喜欢就支持一下吧
点赞10 分享