MySQL-统计出现的各个子字符串(keyword)及其个数
一、需求分析
二、设计思路
三、存储过程实现
四、遇到的问题及处理方法
五、用到的函数及过程控制关键字
一、需求分析
源数据:
目标数据:
二、设计思路
根据源数据、目标数据的格式,要统计每个keyword出现的总次数,必须想办法把每个keyword单独摘出来——以‘,’为分割符,把每个record的keyword先insert到临时表KW,最后group by再count即可。
第一步:外层循环结合游标,单独处理每个record;
第二步:内层循环使用各字符串函数,将每个record里的keyword insert到KW表;
第三步:对KW的data统计即可;
三、存储过程实现
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 //
四、遇到的问题及处理方法
问题描述:编码为UTF8,每个汉字占3个字符,在使用‘substr('牛仔,牛仔裤,裤',length('牛仔')+3)’不能得到理想的值。
解决办法:如果不是汉字字符是英文字符的话,那么上述方法可行。关键还是substr函数理解的问题,substr的关键是返回position及其后的字符(The forms without a len argument return a substring from string str starting atposition pos.)
详见下列2张图片结果对比:
英文字符:
中文字符:
五、用到的函数及过程控制关键字
函数:replace、substring_index、substr、length、count
过程控制:Cursor、Handler、If、Repeat