爱程序网

MySQL-procedure(cursor,loop)

来源: 阅读:

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

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

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

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

 1 drop procedure if exists proc134f; 2 create procedure proc134f() 3 begin 4 declare kidoo int; 5 declare tid int; 6 declare stroo int; 7 declare str varchar(255); 8 declare strlength int; 9 declare istr varchar(3);10 declare istr_cnt int;11 declare done int;  -- 游标用12 declare cur_kid cursor for select kid from spam_keyword;  -- 游标用13 declare continue handler for not found set done=1; -- 游标用,据说是直达引擎的通道14 set tid=0;15 delete from t;16 open cur_kid;  -- 开启游标17 loop1:loop  -- 开启1层外循环18 fetch cur_kid into kidoo;  -- 从定义的范围中读取下一行并赋予19 if done=1 then leave loop1;end if;  -- 判断是否 found 下一行,否则跳出20     select word into str from spam_keyword where kid=kidoo;21     set str=replace(str,' ','');  -- 去掉空格22     set strlength=char_length(str);23     set stroo=0;24         loop2:loop  -- 2层内循环25         set stroo=stroo+1;26         set istr=substr(str,stroo,1);27         select count(*) into istr_cnt from t where t=istr;  -- 计数28             if istr_cnt<>0 then update t set cnt=cnt+1 where t=istr;else29             set tid=tid+1;30             insert into t set id=tid,t=istr,cnt=1;end if;31         if stroo>=strlength then leave loop2;end if;end loop loop2;32     33 set done=0;34 end loop loop1;35 close cur_kid;  -- 关闭游标36 select * from t order by cnt desc;37 END;

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

 1 +-----+----+-----+ 2 | id  | t  | cnt | 3 +-----+----+-----+ 4 |  31 ||  42 | 5 | 236 ||  40 | 6 |   2 ||  37 | 7 | 156 | 0  |  27 | 8 |  51 ||  26 | 9 | 202 ||  26 |10 | 107 ||  24 |11 | 150 | 1  |  24 |12 |   6 ||  22 |13 | 154 | 5  |  21 |14 .15 ..16 ...省略1000行左右17 | 1015 ||   1 |18 | 1016 ||   1 |19 | 1017 ||   1 |20 | 1018 ||   1 |21 | 1019 ||   1 |22 | 1020 ||   1 |23 | 1021 ||   1 |24 | 1022 ||   1 |25 | 1023 ||   1 |26 +------+----+-----+

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

相关文章列表:
关于爱程序网 - 联系我们 - 广告服务 - 友情链接 - 网站地图 - 版权声明 - 人才招聘 - 帮助