mysql如何進行以,分割的字符串的拆分

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

str: 要處理的字符串sql

delim: 分割符函數

count: 計數 若是爲正數,則從左開始數,若是爲負數,則從右開始數設計

例:字符串

str = 'www.baidu.com';string

 

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);test

相關文章
相關標籤/搜索