首页 > 技术文章 > mysql如何进行以,分割的字符串的拆分

staticed 2018-03-12 14:51 原文

在mysql中提供了一些字符串操作的函数,其中SUBSTRING_INDEX(str, delim, count)

str: 要处理的字符串

delim: 分割符

count: 计数 如果为正数,则从左开始数,如果为负数,则从右开始数

例:

str = 'www.baidu.com';

 

SELECT substring_index('www.baidu.com','.', 1);    #www
 
SELECT substring_index('www.baidu.com','.', 2);    #www.baidu
 
SELECT substring_index('www.baidu.com','.', -1);   #com
 
SELECT substring_index('www.baidu.com','.', -2);   #baidu.com
 
SELECT substring_index(substring_index('www.baidu.com','.', -2), '.', 1);  #baidu
 
有了这个函数的帮助,我们还需要确定什么呢?需要知道  当前要分割的位置
如何来获取当前要分割的位置呢?我们可以先获取总共能拆分成多少个字符串
SELECT LENGTH('1,2,3,4,5,6,7') - LENGTH(REPLACE('1,2,3,4,5,6,7', ',', '')) + 1;
结果为7,那么其实我们想要的就是遍历1到6,分别获取当前位置的字符串:SELECT substring_index(substring_index('1,2,3,4,5,6,7',',', index), ',', -1)
其中index就是我们要遍历的位置,所以为了遍历,我们需要一个关联一个辅助表来得到当前位置,最后的设计如下:

SELECT substring_index(substring_index(t.context,',', b.help_topic_id + 1), ',', -1) FROM test.test t join mysql.help_topic b ON b.help_topic_id < (LENGTH(t.context) - LENGTH(REPLACE(t.context, ',', '')) + 1);

 

推荐阅读