我这边直接说案例(能解决什么样的问题)
关于Mysql游标的语法含义,还请百度了解。
如图1,需求是,从上往下,相同的name1,score进行累加统计,得到图2;
不是简单的进行Group by的操作。因为结果集会出现相同的name1行
实现代码如下:我将游标循环写在了存储过程里,也可以直接在查询语句中执行;
--原始数据
create table tests01(name1 varchar(10),score int)
insert into tests01(name1,score)
values("甲",10),("甲",20),("乙",10),("乙",30),("乙",20),("乙",30),("甲",10),("丙",20),("丙",30),("丁",10),("丁",10),("甲",40)
--整合后数据
create table tests01_des(id int primary key auto_increment , name1 varchar(10),score int);
--创建存储过程
DELIMITER $$
CREATE PROCEDURE `StatisticStore`()
BEGIN
declare done INT DEFAULT 0;
declare name2 varchar(10);
declare score2 int;
DECLARE MAXID INT;
declare cur_test cursor for select name1,score from tests01;
DECLARE CONTINUE HANDLER FOR NOT FOUND SET done=1;
open cur_test;
repeat
fetch cur_test into name2,score2;
if not done then
begin
if ((select count(1) from tests01_des)=0) then
insert into tests01_des(name1,score) values(name2,score2);
else
begin
if (select name1 from tests01_des order by id desc limit 1)=name2 then
SET MAXID=( select max(id) from tests01_des);
update tests01_des set score = score+score2 where id=MAXID;
else
insert into tests01_des(name1,score) values(name2,score2);
end if;
end;
end if;
end;
end if;
until done end repeat;
close cur_test;
END$$
DELIMITER ;
--调用执行过程
call StatisticStore();
--查看数据
select * from tests01;
select* from tests01_des;
其他思路:
也可以将原始表添加自增列,然后使用while循环依次获取表内容进行简单的循环操作,就可以不使用游标啦!
哈哈哈哈哈,等待下班的孩子。。。。