《Mysql入門mysql 列轉(zhuǎn)行的技巧(分享)》要點:
本文介紹了Mysql入門mysql 列轉(zhuǎn)行的技巧(分享),希望對您有用。如果有疑問,可以聯(lián)系我們。
前言:MYSQL數(shù)據(jù)庫
由于很多業(yè)務(wù)表因為歷史原因或者性能原因,都使用了違反第一范式的設(shè)計模式.即同一個列中存儲了多個屬性值(具體結(jié)構(gòu)見下表).MYSQL數(shù)據(jù)庫
這種模式下,應(yīng)用常常需要將這個列依據(jù)分隔符進行分割,并得到列轉(zhuǎn)行的結(jié)果.MYSQL數(shù)據(jù)庫
表數(shù)據(jù):MYSQL數(shù)據(jù)庫
期望得到結(jié)果:MYSQL數(shù)據(jù)庫
ID | Value |
1 | tiny |
1 | small |
1 | big |
2 | small |
2 | medium |
3 | tiny |
3 | big |
正文:
MYSQL數(shù)據(jù)庫
#需要處理的表 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'); #用于循環(huán)的自增表 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 <= (length(a.mSize) - length(replace(a.mSize,',',''))+1) order by a.ID;
原理分析:MYSQL數(shù)據(jù)庫
這個join最基本原理是笛卡爾積.通過這個方式來實現(xiàn)循環(huán).MYSQL數(shù)據(jù)庫
以下是具體問題分析:MYSQL數(shù)據(jù)庫
length(a.Size) - length(replace(a.mSize,',',''))+1? 表示了,按照逗號分割后,改列擁有的數(shù)值數(shù)量,下面簡稱nMYSQL數(shù)據(jù)庫
join過程的偽代碼:MYSQL數(shù)據(jù)庫
根據(jù)ID進行循環(huán)MYSQL數(shù)據(jù)庫
{MYSQL數(shù)據(jù)庫
判斷:i 是否 <= nMYSQL數(shù)據(jù)庫
{MYSQL數(shù)據(jù)庫
獲取最靠近第 i 個逗號之前的數(shù)據(jù), 即 substring_index(substring_index(a.mSize,',',b.ID),',',-1)MYSQL數(shù)據(jù)庫
i = i +1MYSQL數(shù)據(jù)庫
}MYSQL數(shù)據(jù)庫
ID = ID +1MYSQL數(shù)據(jù)庫
}MYSQL數(shù)據(jù)庫
總結(jié):MYSQL數(shù)據(jù)庫
這種方法的缺點在于,我們需要一個擁有連續(xù)數(shù)列的獨立表(這里是incre_table).并且連續(xù)數(shù)列的最大值一定要大于符合分割的值的個數(shù).MYSQL數(shù)據(jù)庫
例如有一行的mSize 有100個逗號分割的值,那么我們的incre_table 就需要有至少100個連續(xù)行.MYSQL數(shù)據(jù)庫
當(dāng)然,mysql內(nèi)部也有現(xiàn)成的連續(xù)數(shù)列表可用.如mysql.help_topic: help_topic_id 共有504個數(shù)值,一般能滿足于大部分需求了.MYSQL數(shù)據(jù)庫
改寫后如下:MYSQL數(shù)據(jù)庫
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;
以上這篇mysql 列轉(zhuǎn)行的技巧(分享)就是小編分享給大家的全部內(nèi)容了,希望能給大家一個參考,也希望大家多多支持維易PHP.MYSQL數(shù)據(jù)庫
轉(zhuǎn)載請注明本頁網(wǎng)址:
http://www.fzlkiss.com/jiaocheng/1666.html