MySQL逗號(hào)分割字段的行列轉(zhuǎn)換技巧
瀏覽量:2552
CRM定制請(qǐng)找易勢(shì)科技
表數(shù)據(jù):
|
ID |
Value |
|
1 |
tiny,small,big |
|
2 |
small,medium |
|
3 |
tiny,big |
期望得到結(jié)果:
|
ID |
Value |
|
1 |
tiny |
|
1 |
small |
|
1 |
big |
|
2 |
small |
|
2 |
medium |
|
3 |
tiny |
|
3 |
big |
正文:
#需要處理的表
createtable tbl_name (ID int ,mSize varchar(100));
insertinto tbl_name values (1,'tiny,small,big');
insertinto tbl_name values (2,'small,medium');
insertinto tbl_name values (3,'tiny,big');
#用于循環(huán)的自增表
createtable incre_table (AutoIncreID int);
insertinto incre_table values (1);
insertinto incre_table values (2);
insertinto incre_table values (3);
selecta.ID,substring_index(substring_index(a.mSize,',',b.AutoIncreID),',',-1)
from
tbl_name a
join
incre_table b
onb.AutoIncreID <= (length(a.mSize) - length(replace(a.mSize,',',''))+1)
orderby a.ID;
原理分析:
這個(gè)join最基本原理是笛卡爾積。通過(guò)這個(gè)方式來(lái)實(shí)現(xiàn)循環(huán)。
以下是具體問(wèn)題分析:
length(a.Size) - length(replace(a.mSize,',',''))+1 表示了,按照逗號(hào)分割后,改列擁有的數(shù)值數(shù)量,下面簡(jiǎn)稱n
join過(guò)程的偽代碼:
根據(jù)ID進(jìn)行循環(huán)
{
判斷:i 是否<= n
{
獲取最靠近第i 個(gè)逗號(hào)之前的數(shù)據(jù),即substring_index(substring_index(a.mSize,',',b.ID),',',-1)
i = i +1
}
ID = ID +1
}
總結(jié):
這種方法的缺點(diǎn)在于,我們需要一個(gè)擁有連續(xù)數(shù)列的獨(dú)立表(這里是incre_table)。并且連續(xù)數(shù)列的最大值一定要大于符合分割的值的個(gè)數(shù)。
例如有一行的mSize 有100個(gè)逗號(hào)分割的值,那么我們的incre_table 就需要有至少100個(gè)連續(xù)行。
當(dāng)然,mysql內(nèi)部也有現(xiàn)成的連續(xù)數(shù)列表可用。如mysql.help_topic:help_topic_id 共有504個(gè)數(shù)值,一般能滿足于大部分需求了。
改寫后如下:
selecta.ID,substring_index(substring_index(a.mSize,',',b.help_topic_id+1),',',-1)
from
tbl_name a
join
mysql.help_topic b
onb.help_topic_id < (length(a.mSize) - length(replace(a.mSize,',',''))+1)
orderby a.ID;

