Skip to main content
deleted 2 characters in body
Source Link

Because your paging based on the parent accounts only, you first need to locationcalculate the limit and offset of the records in question.

Because your paging based on the parent accounts only, you first need to location the limit and offset of the records in question.

Because your paging based on the parent accounts only, you first need calculate the limit and offset of the records in question.

Source Link

Here is an example on how you can accomplish this.

setting up the data...

drop table if exists account;
create table account
(
    accountid       char(36) not null default '' comment 'key'
  , accountparentid char(36) default null comment 'Id root node'
  , createddate     datetime default null comment 'created date'
  , primary key (accountid)
);


INSERT INTO account VALUES 
 ("1", "null", "2001-01-02"),
 ("2", "1", "2001-02-02"),
 ("3", "2", "2001-03-02"),    
 ("4", "null", "2001-04-02"),
 ("5", "4", "2001-05-02"), 
 ("6", "null", "2001-06-02");


drop procedure if exists proc_account_pagination;

Because your paging based on the parent accounts only, you first need to location the limit and offset of the records in question.

create procedure proc_account_pagination (in p_pagenumber int, in p_pagesize int)
begin
    
    declare v_offset int;
    set v_offset = (p_pagenumber - 1) * p_pagesize;

Then insert those records into a temp table, you can also use an in-line sub query, dealers choice here... (note I'm using ..where accountparentid = 'null' because you're inserting them in your example as char, fixing the data types is recommended :) )

    drop temporary table if exists temp_page;
    create temporary table temp_page
    select
        accountid
      , accountparentid
      , cast(createddate as char(200)) as createddate
      , cast(accountid as char(200))   as path
      , 0                              as depth
    from account
    where accountparentid = 'null'
    limit p_pagesize offset v_offset;

Now run a similar recursive cte to gather the children

    with recursive accounttree
    as
    (
            select
                accountid
              , accountparentid
              , createddate
              , path
              , depth
            from temp_page
            union all
            select
                va.accountid
              , va.accountparentid
              , accounttree.createddate
              , concat(accounttree.path, ',', va.accountid)
              , accounttree.depth + 1
            from account va
                join accounttree
                    on accounttree.accountid = va.accountparentid
    )
    select
        row_number() over (
            order by
            createddate desc) as rowindex
      , accountid
      , accountparentid
      , path
      , depth
    from accounttree
        order by
        path;

end;

And finally test it, good luck!

call proc_account_pagination(1, 3);