我正在使用嵌套游标来检索许多不同人的最后一小时的工作。 为此,我首先获取第一个光标中每个人的 id,并将这些 id 发送到第二个光标,第二个光标为每个人的 id 选择最大(小时)。返回的值是正确的,但显示的结果是重复的,除非当我单独测试第一个光标时,它只显示每个 id 的一个结果。 也许答案很容易看出,但经过多次尝试解决后我还是看不出来。感谢您的帮助。 这是我的代码:
block 1:
BEGIN
DECLARE no_more_rows INT DEFAULT FALSE;
DECLARE v_idChauffeur VARCHAR(7);
DECLARE c_idChauffeur CURSOR FOR
SELECT DISTINCT id_chauffeur FROM temp
RIGHT JOIN chauffeur
ON temp.logon = chauffeur.matricule_chauffeur
WHERE logon IN (SELECT matricule_chauffeur from chauffeur)
order by id_chauffeur;
DECLARE CONTINUE HANDLER FOR NOT FOUND SET no_more_rows = TRUE;
OPEN c_idChauffeur;
get_idChauffeur:LOOP
FETCH c_idChauffeur INTO v_idChauffeur;
IF no_more_rows THEN CLOSE c_idChauffeur;
LEAVE get_idChauffeur;
END IF;
block 2:
BEGIN
DECLARE no_more_rows2 INT DEFAULT FALSE;
DECLARE v_maxHeure VARCHAR(20);
DECLARE c_maxHeure CURSOR FOR
SELECT DISTINCT(max(heure)) as heure from temp
right join chauffeur ON temp.logon = chauffeur.matricule_chauffeur
where id_chauffeur = v_idChauffeur
order by heure;
DECLARE CONTINUE HANDLER FOR NOT FOUND SET no_more_rows2 = TRUE;
OPEN c_maxHeure;
get_maxHeure:LOOP
FETCH c_maxHeure INTO v_maxHeure;
SELECT v_maxHeure,v_idChauffeur;
IF no_more_rows2 THEN CLOSE c_maxHeure;
LEAVE get_maxHeure;
END IF;
END LOOP get_maxHeure;
END BLOCK2;
END LOOP get_idChauffeur;
END BLOCK1
以下是一些重复的结果:
v_maxHeure 23:02:17 v_idChauffeur 93
v_maxHeure 23:02:17 v_idChauffeur 93
v_maxHeure 23:24:12 v_idChauffeur 99
v_maxHeure 23:24:12 v_idChauffeur 99
v_maxHeure 15:19:28 v_idChauffeur 100
v_maxHeure 15:19:28 v_idChauffeur 100
感谢您的帮助
最佳答案
对于相当简单的数据库任务来说,代码看起来确实很复杂。 根据代码的假设,有两个表(temp 和 chauffeur)与“temp.logon = chauffeur.matricule_chauffeur”连接。 现在您想要获取 Max(hour)(即 max(temp.heure))和人员 ID(即 id_chauffeur)的不同记录。 我相信上述任务可以通过如下一个相当简单的查询来实现。
SELECT DISTINCT(max(temp.heure)) as heure, temp.id_chauffeur
FROM temp INNER JOIN chauffeur ON temp.logon = chauffeur.matricule_chauffeur
ORDER BY temp.heure;
(注意:我刚刚通过空运行编译了查询,因为我没有表结构。希望它对您有用......干杯!)
关于mysql - 为什么我的嵌套光标显示两倍的结果?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55092120/