递归调用自身的mysql存储过程

2021-11-20 00:00:00 递归 mysql stored-procedures

我有下表:

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

现在我需要 mysql 中的一个存储过程,它递归地调用自己并返回计算出的数量.例如,id 6 的父值为 5,父值为 3,父值为 2.所以我需要计算 4 * 2 * 10 * 3 ( = 240) 结果.

Now I need a stored procedure in mysql that calls itself recursively and returns the computed quantity. For example the id 6 has 5 as a parent which as 3 as a parent which has 2 as a parent. So I need to compute 4 * 2 * 10 * 3 ( = 240) as a result.

我对存储过程还很陌生,以后不会经常使用它们,因为我更喜欢将业务逻辑放在程序代码中而不是数据库中.但在这种情况下,我无法避免.

I am fairly new to stored procedures and I won't use them very often in the future because I prefer having my business logic in my program code rather then in the database. But in this case I can't avoid it.

也许一个 mysql 大师(就是你)可以在几秒钟内编写一个工作语句.

Maybe a mysql guru (that's you) can hack together a working statement in a couple of seconds.

推荐答案

仅在mysql版本>=5

its work only in mysql version >= 5

存储过程声明是这样的,

the stored procedure declaration is this,

你可以给它一点改进,但​​这个工作:

you can give it little improve , but this working :

DELIMITER $$

CREATE PROCEDURE calctotal(
   IN number INT,
   OUT total INT
)

BEGIN

   DECLARE parent_ID INT DEFAULT NULL ;
   DECLARE tmptotal INT DEFAULT 0;
   DECLARE tmptotal2 INT DEFAULT 0;

   SELECT parentid   FROM test   WHERE id = number INTO parent_ID;   
   SELECT quantity   FROM test   WHERE id = number INTO tmptotal;     

   IF parent_ID IS NULL
    THEN
    SET total = tmptotal;
   ELSE     
    CALL calctotal(parent_ID, tmptotal2);
    SET total = tmptotal2 * tmptotal;   
   END IF;

END$$

DELIMITER ;

呼叫就像(设置这个变量很重要):

the calling is like (its important to set this variable) :

SET @@GLOBAL.max_sp_recursion_depth = 255;
SET @@session.max_sp_recursion_depth = 255; 

CALL calctotal(6, @total);
SELECT @total;

相关文章