递归与MYSQL?
我有一个非常简单的表结构,如下所示:
Table Page Hits
id | title | parent | hits
---------------------------
1 | Root | | 23
2 | Child | 1 | 20
3 | ChildX | 1 | 30
4 | GChild | 2 | 40
由于我不想在代码中使用递归,所以我想做一个递归 SQL。
是否有任何 SELECT 语句可以获取 Root
(23+20+30+40) 或 Child
(20 + 40) 的总和?
I got a really simple table structure like this:
Table Page Hits
id | title | parent | hits
---------------------------
1 | Root | | 23
2 | Child | 1 | 20
3 | ChildX | 1 | 30
4 | GChild | 2 | 40
As I don't want to have the recursion in my code I would like to do a recurisive SQL.
Is there any SELECT statement to get the sum of Root
(23+20+30+40) or Child
( 20 + 40 ) ?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您正在使用邻接列表模型来组织分层数据。事实上,这种递归操作很困难,这是该模型的一个主要缺点。
某些 DBMS,例如 SQL Server 2005、Postgres 8.4 和 Oracle 11g,支持使用公用表表达式 与
WITH
关键字。至于 MySQL,您可能有兴趣查看以下文章,其中描述了另一种模型(嵌套集合模型),这使得递归操作更容易(可能):
You are organizing your hierarchical data using the adjacency list model. The fact that such recursive operations are difficult is in fact one major drawback of this model.
Some DBMSes, such as SQL Server 2005, Postgres 8.4 and Oracle 11g, support recursive queries using common table expressions with the
WITH
keyword.As for MySQL, you may be interested in checking out the following article which describes an alternative model (the nested set model), which makes recursive operations easier (possible):
不在 1 个选择语句中,没有。
如果您知道关系的最大深度(即父级->子级->子级或父级->子级->子级->子级),您可以编写一条 select 语句,该语句将为您提供一堆数字,然后你必须单独求和(每个深度级别 1 个数字)。
但是,您可以使用递归的 mysql 存储过程来完成此操作。
Not in 1 select statment, no.
If you knew the maximum depth of the relationshop (ie parent->child->child or parent->child->child->child) you could write a select statement which would give you a bunch of numbers that you would then have to sum up seperately (1 number per level of depth).
You could, however, do it with a mysql stored procedure which is recursive.