CREATE PROCEDURE StatisticStore3()
BEGIN
declare _n varchar(20);
declare done int default false;
declare cur cursor for select name from store group by name;
declare continue HANDLER for not found set done = true;
open cur;
read_loop:loop
fetch cur into _n;
if done then
leave read_loop;
end if;
begin
declare c int;
declare n varchar(20);
declare total int default 0;
declare done int default false;
declare cur cursor for select name,count from store where name = 'iphone';
declare continue HANDLER for not found set done = true;
set total = 0;
open cur;
iphone_loop:loop
fetch cur into n,c;
if done then
leave iphone_loop;
end if;
set total = total + c;
end loop;
close cur;
select _n,n,total;
end;
begin
declare c int;
declare n varchar(20);
declare total int default 0;
declare done int default false;
declare cur cursor for select name,count from store where name = 'android';
declare continue HANDLER for not found set done = true;
set total = 0;
open cur;
android_loop:loop
fetch cur into n,c;
if done then
leave android_loop;
end if;
set total = total + c;
end loop;
close cur;
select _n,n,total;
end;
begin
end;
end loop;
close cur;
END;//
mysql> call StatisticStore3()//
+---------+--------+-------+
| _n | n | total |
+---------+--------+-------+
| android | iphone | 47 |
+---------+--------+-------+
1 row in set (0.01 sec)
+---------+---------+-------+
| _n | n | total |
+---------+---------+-------+
| android | android | 33 |
+---------+---------+-------+
1 row in set (0.01 sec)
+--------+--------+-------+
| _n | n | total |
+--------+--------+-------+
| iphone | iphone | 47 |
+--------+--------+-------+
1 row in set (0.01 sec)
+--------+---------+-------+
| _n | n | total |
+--------+---------+-------+
| iphone | android | 33 |
+--------+---------+-------+
1 row in set (0.01 sec)
Query OK, 0 rows affected (0.01 sec)
我想请教一下mysql5.7 ,使用嵌套游标,但是他显示多循环了1次的结果...求解
这是Mysql 5.7.19 版本
最开始的时候我定义了 游标的语句是使用group by name的结果来循环
那正常是不是应显示 android 和 iphone 各一次的结果才是对的呢
调用时如下结果输出
mysql> select @@tx_isolation//
+-----------------+
| @@tx_isolation |
+-----------------+
| REPEATABLE-READ |
+-----------------+
1 row in set (0.00 sec)
mysql> call StatisticStore3()//
+---------+--------+-------+
| _n | n | total |
+---------+--------+-------+
| android | iphone | 47 |
+---------+--------+-------+
1 row in set (0.01 sec)
+---------+---------+-------+
| _n | n | total |
+---------+---------+-------+
| android | android | 33 |
+---------+---------+-------+
1 row in set (0.01 sec)
+--------+--------+-------+
| _n | n | total |
+--------+--------+-------+
| iphone | iphone | 47 |
+--------+--------+-------+
1 row in set (0.01 sec)
+--------+---------+-------+
| _n | n | total |
+--------+---------+-------+
| iphone | android | 33 |
+--------+---------+-------+
1 row in set (0.01 sec)
Query OK, 0 rows affected (0.01 sec)