在一个条件下使用while循环对多行进行分组

vlju58qv  于 2021-06-19  发布在  Mysql
关注(0)|答案(0)|浏览(257)

在mysql中,我有一个这样的表:这有点复杂,因为mysql不支持排名窗口函数,甚至不支持ctes,所以我尝试使用while循环来实现它

如果导入的和节之间存在任何关系,则应将它们分组在一起。根据关系,它们应分为1、2、3、4、,。。。。
但在这个场景中,我的rn总是1,不知道为什么它不会递增。你能帮我复习一下这个问题吗?我不知道该怎么办。
创建脚本示例:

create table temp1 (
    id int, imported int, section int, rn int, checked int default 0
    );
    insert into temp1(id, section, rn)           values (204, 718, 0);
    insert into temp1(id, imported, section, rn) values (997,718,034,0);
    insert into temp1(id, imported, section, rn) values (998,034,055,0);
    insert into temp1(id, imported, section, rn) values (111,453,234,0);
    insert into temp1(id, section, rn) values (908, 453,0);
    insert into temp1(id, imported, section, rn) values (231,234,890,0);
    insert into temp1(id, section, rn) values (342, 567,0);

我的最终结果应该是:

我也尝试过while循环创建存储过程:

DROP PROCEDURE IF EXISTS sp_recursiveimport;
    Delimiter $$
    CREATE PROCEDURE sp_recursiveimport()  -- (IN rnX integer)
    BEGIN
    DECLARE n INT DEFAULT 0;   DECLARE i,j,k INT DEFAULT 0;    SELECT COUNT(*) FROM temp1 INTO n;
    SET i=0; set @rn = 1; --  set @k = 0;
    WHILE i<n DO 
    set j = 0; select i;
      set @sec = (select ifnull(section,0) FROM temp1 LIMIT i,1);          
      set @imp = (select ifnull(imported,0) FROM temp1 LIMIT i,1); select @imp, @sec;
        update1: while j<n do   select j;
    --         if j=0 then
               if (select ifnull(imported,0) from temp1 limit j,1) = @sec and (select checked from temp1 limit j,1) = 0 then 
               set @update  = concat('update temp1 set rn = 1, checked = 1 where imported = ',@sec); select @update;    PREPARE stmt_name FROM @update;     EXECUTE Stmt_name;     DEALLOCATE prepare stmt_name;
               set @update1 = concat('update temp1 set rn = 1, checked = 1 where section = ',@sec); select @update1;   PREPARE stmt_name FROM @update1;     EXECUTE Stmt_name;     DEALLOCATE prepare stmt_name;
               set k = j;
               end if;
               if (select ifnull(section,0)          from temp1 limit j,1) = @imp and (select checked from temp1 limit j,1) = 0 then 
               set @update3 = concat('update temp1 set rn = 1, checked = 1 where section = ',@imp);  select @update3;    PREPARE stmt_name FROM @update3;     EXECUTE Stmt_name;     DEALLOCATE prepare stmt_name;
               set @update4 = concat('update temp1 set rn = 1, checked = 1 where imported = ',@imp); select @update4;    PREPARE stmt_name FROM @update4;     EXECUTE Stmt_name;     DEALLOCATE prepare stmt_name;
               set k = j;
               end if;

    --            set @sec = (select ifnull(imported,0) from temp1 limit k,1);
    --            set @imp = (select ifnull(section,0)          from temp1 limit k,1); select @sec, @imp;
        set j= j+1;
        end while update1;

      set i = i + 1;
    END WHILE;
    END;
    $$
    delimiter;

不知道为什么不行。

暂无答案!

目前还没有任何答案,快来回答吧!

相关问题