需求
MySQL中,某個字段通過分隔符保存了多個字符串,如下:
需要將字段中的字符串分成不同的行,如下:
用到的知識
MySQL提供了一系列字符串處理函數
1、left(str, len)
:從左邊開始截取指定長度
2、right(str, len)
:從右邊開始截取指定長度
3、substring(str, pos)
:從第pos個字符開始截取(注意從1開始計數)
- 當pos為正數:從左往右數第pos個
- 當pos為負數:從右往左數第pos個
比如pos為-2,字符串為"a,b,c",截取結果為",c"
4、substring(str, pos, len)
:從第pos個字符開始截取指定長度(注意從1開始計數)
5、substring_index(str, delim, count)
:根據delim分隔符進行分割,從頭開始截取到第count個分隔符之前
select id, substring_index("a,b,c", ',', 2) from test_split;
截取到第二個分隔符之前
最終實現
實現效果
select
b.help_topic_id + 1 as id,
substring_index(substring_index(a.name, ',', b.help_topic_id + 1) ,',', -1) as name
from
test_split a join mysql.help_topic b
on
b.help_topic_id < LENGTH(a.name) - LENGTH(REPLACE(a.name,',','')) + 1;
一行變成多行,需要借助輔助表,這里選擇mysql.help_topic
mysql.help_topic表的id特點是從0開始遞增,最大為700
1、分割成多少份:LENGTH(a.name) - LENGTH(REPLACE(a.name, ',' , '')) + 1
- length('a,b,c') - length( replace('a,b,c', ',', '') ) + 1 = 5 - 3 + 1 = 3
- 原始長度 - 去掉分隔符,之后的長度 = 分隔符數量
- 分隔符數量 + 1 = 被分割的數量
2、獲取分割之后的每一份字符串
2.1、substring_index(a.name, ',', b.help_topic_id + 1)
:隨着help_topic_id
增加,截取的字符串依次增加,"a"、"a,b"、"a,b,c"……
2.2、substring_index(str, ',' , -1)
:獲取str按分隔符分割之后的最后一個字符串
substring_index(substring_index(a.name, ',', b.help_topic_id + 1) , ',', -1)
由2.1可知,隨着help_topic_id
增加,依次獲取"a" "b" "c"……