统计个数字符mysql_MySQL-统计出现的各个子字符串(keyword)及其个数

这篇博客介绍了如何在MySQL中统计以逗号分隔的子字符串(keyword)及其出现次数。通过存储过程实现,首先利用游标处理每个记录,再通过字符串函数提取关键词并插入临时表,最后进行分组计数。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

MySQL-统计出现的各个子字符串(keyword)及其个数

一、需求分析

二、设计思路

三、存储过程实现

四、遇到的问题及处理方法

五、用到的函数及过程控制关键字

一、需求分析

源数据:

0818b9ca8b590ca3270a3433284dd417.png

0818b9ca8b590ca3270a3433284dd417.png

0818b9ca8b590ca3270a3433284dd417.png

目标数据:

0818b9ca8b590ca3270a3433284dd417.png

0818b9ca8b590ca3270a3433284dd417.png

0818b9ca8b590ca3270a3433284dd417.png

二、设计思路

根据源数据、目标数据的格式,要统计每个keyword出现的总次数,必须想办法把每个keyword单独摘出来——以‘,’为分割符,把每个record的keyword先insert到临时表KW,最后group by再count即可。

第一步:外层循环结合游标,单独处理每个record;

第二步:内层循环使用各字符串函数,将每个record里的keyword insert到KW表;

第三步:对KW的data统计即可;

三、存储过程实现

0818b9ca8b590ca3270a3433284dd417.png

0818b9ca8b590ca3270a3433284dd417.png

0818b9ca8b590ca3270a3433284dd417.png

delimiter //

create procedure word_count()

begin

/*declare for variables*/

declare done int default 0;

declare delim char(6);

declare ndelim int default 0;

declare keyword,remainstr varchar(100);

declare j int default 0;

/*delcare for cursor*/

declare wordrow cursor for

select splitStr from xxm;

/*delcare for exception*/

declare continue handler for not found set done=1;

/*define the delimiter*/

set delim=',';

open wordrow;

wRow:repeat

fetch wordrow into keyword;

/*define where leave wRow*/

if done=1

then

leave wRow;

end if;

set ndelim=(length(keyword)-length(replace(keyword,delim,'')))/length(delim);

set keyword=replace(keyword,' ',''); /*Remove spaces*/

set j=0;

/*insert single keyword into temporary table KW*/

kword:while j<=ndelim

do

insert into KW values(substring_index(keyword,delim,1));

set remainstr=substring_index(keyword,delim,1);

set keyword=substr(keyword,(length(remainstr)+3)/3+1);

set j=j+1;

end while kword;

until done=1

end repeat wRow;

close wordrow;

set done=0;

/*select show the result*/

select word,count(word) from KW group by word;

end //

0818b9ca8b590ca3270a3433284dd417.png

四、遇到的问题及处理方法

问题描述:编码为UTF8,每个汉字占3个字符,在使用‘substr('牛仔,牛仔裤,裤',length('牛仔')+3)’不能得到理想的值。

解决办法:如果不是汉字字符是英文字符的话,那么上述方法可行。关键还是substr函数理解的问题,substr的关键是返回position及其后的字符(The forms without a len argument return a substring from string str starting atposition pos.)

详见下列2张图片结果对比:

英文字符:

0818b9ca8b590ca3270a3433284dd417.png

0818b9ca8b590ca3270a3433284dd417.png

0818b9ca8b590ca3270a3433284dd417.png

中文字符:

0818b9ca8b590ca3270a3433284dd417.png

0818b9ca8b590ca3270a3433284dd417.png

0818b9ca8b590ca3270a3433284dd417.png

五、用到的函数及过程控制关键字

函数:replace、substring_index、substr、length、count

过程控制:Cursor、Handler、If、Repeat

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值