MySQL嵌套游标的问题

时间:2010-07-08 07:44:54

标签: mysql nested cursor cursors

我有以下一堆代码尝试使用2个游标更新字段,另一个使用另一个游标。我使用第一个游标只是获取一个id值(第一个游标),然后我得到一个基于该id(第二个游标)的其他id值列表。问题是第二个游标的结果集包含最后一个id两次!我找不到这个bug!循环中有什么东西,2个游标的终止变量中有什么东西?

任何帮助都超过欢迎!提前谢谢!

DELIMITER $$ DROP PROCEDURE IF EXISTS updateNumberOfPoisForPlacesWithChildren $$ CREATE PROCEDURE updateNumberOfPoisForPlacesWithChildren()     开始         DECLARE single_place_id INT(11);         DECLARE single_unique_parents_id INT(11);         完成DECLARE,temp_number_of_pois,sum_number_of_pois INT DEFAULT 0;

    DECLARE unique_parents_ids CURSOR FOR SELECT DISTINCT `parent_id` FROM `places` WHERE `parent_id` IS NOT NULL;
    DECLARE temp_places_ids CURSOR FOR SELECT `id` FROM `places` WHERE `parent_id` = single_unique_parents_id;
        DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = 1;

    OPEN unique_parents_ids;

    main_loop_for_parent_ids : LOOP
        SET sum_number_of_pois = 0;
        IF done = 1 THEN
            CLOSE unique_parents_ids;
            LEAVE main_loop_for_parent_ids;
        END IF;

        IF NOT done = 1 THEN
            FETCH unique_parents_ids INTO single_unique_parents_id;
            OPEN temp_places_ids;
            main_loop_for_places : LOOP
                IF done = 1 THEN
                    CLOSE temp_places_ids;
                    LEAVE main_loop_for_places;
                END IF;

                IF NOT done = 1 THEN
                    FETCH temp_places_ids INTO single_place_id;
                    SELECT COUNT(`id`) INTO temp_number_of_pois FROM `pois` WHERE `place_id` = single_place_id;
                    SET sum_number_of_pois = sum_number_of_pois + temp_number_of_pois;
                END IF;

            END LOOP;   

            UPDATE `places` SET `number_of_pois`=sum_number_of_pois WHERE `id` = single_unique_parents_id;

        END IF;
    END LOOP;



END$$

DELIMITER;

1 个答案:

答案 0 :(得分:0)

我认为你的问题就在这里......

        IF NOT done = 1 THEN
            FETCH temp_places_ids INTO single_place_id;
            SELECT COUNT(`id`) INTO temp_number_of_pois FROM `pois` WHERE `place_id` = single_place_id;
            SET sum_number_of_pois = sum_number_of_pois + temp_number_of_pois;
        END IF;

当FETCH耗尽结果集时,FETCH将DONE设置为1,但是你继续进行,因为你已经通过了DONE测试。

...也许

 FETCH temp_places_ids INTO single_place_id;
 IF NOT done = 1 THEN
     SELECT COUNT(`id`) INTO temp_number_of_pois FROM `pois` WHERE `place_id` = single_place_id;
     SET sum_number_of_pois = sum_number_of_pois + temp_number_of_pois;
 END IF;