MySQL-procedure(cursor,loop)

时间:2023-12-29 08:15:08

现有一张表spam_keyword,共629条记录,每条记录的word字段的字符数量不等。

 CREATE TABLE `spam_keyword` (
`kid` int(11) NOT NULL,
`word` varchar(255) DEFAULT NULL,
`styles` varchar(50) DEFAULT NULL,
`cids` varchar(100) DEFAULT NULL,
`is_active` smallint(6) DEFAULT NULL,
`tm_add` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,-- 不为空,创建新纪录时设为当前时间
PRIMARY KEY (`kid`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8

要写一个procedure的目的是:根据spam_keyword表中的kid对word列逐行逐字分割到t表中,并且统计每个字的数量。

过程中用了两层循环,外循环游标读行,内循环stroo++读字。

 drop procedure if exists proc134f;
create procedure proc134f()
begin
declare kidoo int;
declare tid int;
declare stroo int;
declare str varchar(255);
declare strlength int;
declare istr varchar(3);
declare istr_cnt int;
declare done int;  -- 游标用
declare cur_kid cursor for select kid from spam_keyword;  -- 游标用
declare continue handler for not found set done=1; -- 游标用,据说是直达引擎的通道
set tid=0;
delete from t;
open cur_kid;  -- 开启游标
loop1:loop  -- 开启1层外循环
fetch cur_kid into kidoo;  -- 从定义的范围中读取下一行并赋予
if done=1 then leave loop1;end if;  -- 判断是否 found 下一行,否则跳出
select word into str from spam_keyword where kid=kidoo;
set str=replace(str,' ','');  -- 去掉空格
set strlength=char_length(str);
set stroo=0;
loop2:loop  -- 2层内循环
set stroo=stroo+1;
set istr=substr(str,stroo,1);
select count(*) into istr_cnt from t where t=istr;  -- 计数
if istr_cnt<>0 then update t set cnt=cnt+1 where t=istr;else
set tid=tid+1;
insert into t set id=tid,t=istr,cnt=1;end if;
if stroo>=strlength then leave loop2;end if;end loop loop2; set done=0;
end loop loop1;
close cur_kid;  -- 关闭游标
select * from t order by cnt desc;
END;

完成后,call proc134f 就可以查看在t表中的结果

 +-----+----+-----+
| id | t | cnt |
+-----+----+-----+
| 31 | 院 | 42 |
| 236 | 医 | 40 |
| 2 | 小 | 37 |
| 156 | 0 | 27 |
| 51 | 中 | 26 |
| 202 | 州 | 26 |
| 107 | 发 | 24 |
| 150 | 1 | 24 |
| 6 | 服 | 22 |
| 154 | 5 | 21 |
.
..
...省略1000行左右
| 1015 | 苑 | 1 |
| 1016 | 泽 | 1 |
| 1017 | 被 | 1 |
| 1018 | 驻 | 1 |
| 1019 | 鲁 | 1 |
| 1020 | 木 | 1 |
| 1021 | 齐 | 1 |
| 1022 | 雅 | 1 |
| 1023 | 友 | 1 |
+------+----+-----+

最终结果共1023行,即在spam_keyword表*出现1023个不重复的字符,包含中文,英文,标点数字。出现次数最多的是“医“,”院”。