SQL字符串按指定的字符拆分

直接上SQL:

SELECT 
   substring_index( substring_index( a.sound_urls, ',', b.help_topic_id + 1 ), ',',- 1 ) surl
FROM
    tab_test a
    JOIN mysql.help_topic b ON b.help_topic_id < (( length( a.sound_urls ) - length( REPLACE ( a.sound_urls, ',', '' ) ))/length(',') + 1 ) 

知识点:

1、substring_index(str, delim, count) 方法

str:需要拆分的字符串;

delim:分隔符,根据此字符来拆分字符串;

count:当 count 为正数,取第 n 个分隔符之前的所有字符; 当 count 为负数,取倒数第 n 个分隔符之后的所有字符

2、mysql.help_topic表中help_topic_id从0自增的特性

3、replace(str, beReplaceStr, replaceStr)

4、length(str)

SQL分析:

substring_index( substring_index( a.sound_urls, ',', b.help_topic_id + 1 ), ',',-1 )

根据help_topic_id的变化来分拆字符,每次都取substring_index( a.sound_urls, ',', b.help_topic_id + 1 )中的最后一个字符

JOIN mysql.help_topic b ON b.help_topic_id < ( length( a.sound_urls ) - length( REPLACE ( a.sound_urls, ',', '' ) ) + 1 ) 

利用( length( a.sound_urls ) - length( REPLACE ( a.sound_urls, ',', '' ) ) + 1 )确定循环拆分的次数,help_topic_id是从0开始

 

你可能感兴趣的:(笔记)