MySQL 字符串分割(Split)函数之 SUBSTRING_INDEX 函数

有时我们需要对某个字段的值进行分割,那我们怎样快速的实现字符串的分割呢?
这时我们就需要用到 SUBSTRING_INDEX 函数了

 

函数:SUBSTRING_INDEX(str,delim,count)
解释:从第 count 个 分割符(delim) 处分割字符串(str),返回子字符串。
参数说明:
    str:将要处理的字符串
    delim :用来分割 str 分割符
    count:第 count 个分割符
返回值:
    若 count 为正,则返回分割符左侧的所有内容(从左侧开始计数);
    若 count 为负,则返回分割符右边的所有内容(从右边开始计数)。

注:分割符是大小写敏感的


示例 一:

 

示例二:

 

例子三:

 

本文用到的代码:

-- 例子一:
set  @str   = 'share_conten_mi_a1_b2_c3';
select SUBSTRING_INDEX(@str, '_', 2)  result_str union all
select SUBSTRING_INDEX(@str, '_', -2);

-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-- 例子二:
-- step1: 先创建一个临时表 
drop temporary table if exists tmp_test;
create temporary table tmp_test
	select 1 id , 1 delim_index union all
	select 2 id , 2 delim_index union all
	select 3 id , 3 delim_index union all
	select 4 id , 4 delim_index union all
	select 5 id , 5 delim_index union all
	select 6 id , 6 delim_index union all
	select 7 id , 7 delim_index union all
	select 8 id , 8 delim_index ;

-- step 2:
set  @str   = 'share_conten_mi_a1_b2_c3'    -- 将要处理的字符串
    ,@delim = '_' ;                      -- 分割符
set @delim_max_index = LENGTH(@Str) - LENGTH(REPLACE(@str, @delim, '')) + 1  ;-- 分割符的最大下标 ; 

select 
	 id     -- 序号
	,delim_index -- 第 n 个 分割符
	,case when  @delim_max_index  >= delim_index                     -- 从左侧开始
		  then  SUBSTRING_INDEX(@str, @delim, delim_index) 
		  else  '已分割完' end str1
				
	,case when  @delim_max_index >= delim_index
		  then  SUBSTRING_INDEX(@str, @delim, delim_index * -1)      -- 从右侧开始
		  else  '已分割完' end str2
				
	,case when  @delim_max_index  >= delim_index                     
		  then  SUBSTRING_INDEX(SUBSTRING_INDEX(@str, @delim, delim_index),'_', -1) 
		  else  '已分割完' end str3
from tmp_test;

-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

-- 例子三:若想将字符串都按分割符分割,并写入一张表里,可 参考下面的例子
set  @str   = 'share_conten_mi_a1_b2_c3'
    ,@delim = '_'
    ,@delim_max_index = LENGTH(@Str) - LENGTH(REPLACE(@str, @delim, '')) + 1 ; 
select SUBSTRING_INDEX(SUBSTRING_INDEX(@str, @delim, delim_index),'_', -1) str from tmp_test
where @delim_max_index >= delim_index;

参考:https://dev.mysql.com/doc/refman/8.0/en/string-functions.html#function_substring-index

  • 3
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值