递归调用自身的mysql存储过程
我有下表:
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) 作为结果。
我对存储过程相当陌生,将来不会经常使用它们,因为我更喜欢将业务逻辑放在程序代码中而不是放在数据库中。但在这种情况下我无法避免。
也许 mysql 大师(就是你)可以在几秒钟内拼凑出一个工作语句。
I have the following table:
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
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.
Maybe a mysql guru (that's you) can hack together a working statement in a couple of seconds.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
它仅在 mysql 版本 >= 5 中工作,
存储过程声明是这样的,
您可以对其进行一点改进,但是可以工作:
调用就像
(设置这个变量很重要):
its work only in mysql version >= 5
the stored procedure declaration is this,
you can give it little improve , but this working :
the calling is like
(its important to set this variable) :
查看 Mike Hillyer 撰写的管理 MySQL 中的分层数据。
它包含处理分层数据的完整示例。
Take a look at Managing Hierarchical Data in MySQL by Mike Hillyer.
It contains fully worked examples on dealing with hierarchical data.
如何避免程序:
查看 Fiddle!
注意!如果行的
parent_id>id
则此方法不起作用。干杯!
How about avoiding procedures:
Check out Fiddle!
Note! this will not work if row's
parent_id>id
.Cheers!