MySQL如何用分隔符分隔字符串

2022-10-07,,,,

mysql分隔符分隔字符串

使用

可以使用如下函数

substring_index( i.final_car_type, ' ', 1 )
  • i.final_car_type 即 需要分隔的字符串
  • ’ ’ 即 用空格分隔该字符串
  • 1 即:取出该空格之前的所有字符

也就是说,如果count是正数,那么就是从左往右数,第n个分隔符的左边的全部内容。相反,如果是负数,那么就是从右边开始数,第n个分隔符右边的所有内容

效果

如果count 是1

  • 表里数据:东风风神全新ax7马赫版 df 21(天窗版)
  • 拆分后:东风风神全新ax7马赫版

如果count 是-1

  • 表里数据:东风风神全新ax7马赫版 df 21(天窗版)
  • 拆分后:21(天窗版)

mysql存储过程 根据分隔符拆分字符串

delimiter $$
 
create definer=`root`@`%` procedure `proc_split_id`(in selectids blob(65535),
in splitchar varchar(2))
begin
set @i=0; 
create temporary table if not exists id_result_s(id long not null);
truncate table id_result_s;
set @cnt = 1+(length(selectids) - length(replace(selectids,splitchar,''))); 
set @i=1; 
	start transaction;
    while @i <=@cnt do          
        set @result = replace(substring(substring_index(selectids, splitchar, @i),
       length(substring_index(selectids, splitchar, @i -1)) + 1),
       splitchar, '');  
       insert into id_result_s(id) values (@result );
		set @i = @i + 1;   
    end while;  
	commit;    
end

selectids为需要拆分的字符串,splitchar为分隔符. 拆分的结果保存在临时表id_result_s中.

while中有insert语句,循环插入.在while前后加上start transaction和commit可以提高效率.

以上为个人经验,希望能给大家一个参考,也希望大家多多支持。

《MySQL如何用分隔符分隔字符串.doc》

下载本文的Word格式文档,以方便收藏与打印。