mysql stored procedure that calls itself recursively

后端 未结 4 1963
太阳男子
太阳男子 2020-11-28 14:10

I have the following table:

id | parent_id | quantity
-------------------------
1  | null      | 5
2  | null      | 3
3  | 2         | 10
4  | 2         | 15         


        
4条回答
  •  星月不相逢
    2020-11-28 14:28

    How about avoiding procedures:

    SELECT quantity from (
     SELECT @rq:=parent_id as id, @val:=@val*quantity as quantity from (
      select * from testTable order by -id limit 1000000 # 'limit' is required for MariaDB if we want to sort rows in subquery
     ) t # we have to inverse ids first in order to get this working...
     join
     ( select @rq:= 6 /* example query */, @val:= 1 /* we are going to multiply values */) tmp
     where id=@rq
    ) c where id is null;
    

    Check out Fiddle!

    Note! this will not work if row's parent_id>id.

    Cheers!

提交回复
热议问题