【问题标题】:Mysql, tree, Hierarchical query, performanceMysql,树,分层查询,性能
【发布时间】:2011-08-13 19:54:57
【问题描述】:

我的问题是基于下面的文章(表和函数hierarchy_connect_by_parent_eq_prior_id)http://explainextended.com/2009/03/17/hierarchical-queries-in-mysql/

假设表 t_hierarchy 有两个附加字段(除了 id 和 parent)typ1(char) 和 time(int)。字段 typ1 可以有两个值 A 和 B。 我的目标是按照文章中的描述显示整个树,但我需要在结果中添加一个额外的字段来显示当前节点(如果 typ1 = B)及其所有后代(如果 typ1 = B)的时间。因此,当 typ1=B 时,我需要某个节点(包括其自身)的所有后代时间的总和。

我有以下解决方案,但是太慢了:

主要查询:

 SELECT  CONCAT(REPEAT('    ', level - 1), hi.id) AS treeitem, get_usertime_of_current_node_and_descendants(hi.id) as B_time,
        hierarchy_sys_connect_by_path('/', hi.id) AS path,
        parent, level
FROM    (
        SELECT  hierarchy_connect_by_parent_eq_prior_id(id) AS id,
                CAST(@level AS SIGNED) AS level
        FROM    (
                SELECT  @start_with := 0,
                        @id := @start_with,
                        @level := 0
                ) vars, t_hierarchy
        WHERE   @id IS NOT NULL
        ) ho
JOIN    t_hierarchy hi
ON      hi.id = ho.id

函数get_usertime_of_current_node_and_descendants(input int):

    BEGIN
        DECLARE _id INT;
        DECLARE _desctime INT;
        DECLARE _nodetime INT;
        SET _id = input;

select COALESCE((select sum(time) from (
                SELECT   hi.id, time,typ1
                FROM    (
                        SELECT  hierarchy_connect_by_parent_eq_prior_id_2(id) AS id, @levela AS level
                        FROM    (
                                SELECT  @start_witha := _id,
                                        @ida := @start_witha,
                                        @levela := 0,
                                ) vars, t_hierarchy a
                        WHERE   @ida IS NOT NULL
                        ) ho
                JOIN    t_hierarchy hi
                ON      hi.id = ho.id
                ) q where typ1 = 'B'), 0) into _desctime;
select COALESCE((select time from t_hierarchy where id = _id and typ1='B'), 0) into _nodetime;
return _desctime + _nodetime;

END $$

函数 hierarchy_connect_by_parent_eq_prior_id_2 与本文中的函数和上面的函数 hierarchy_connect_by_parent_eq_prior_id 相同,但它具有不同命名的全局变量,因此不会干扰主查询中使用的变量。

上述解决方案可以正常工作,但速度太慢(尤其是在处理大型数据集时)。您能否提供更好的解决方案或建议如何改进查询?提前感谢您的时间和帮助!

【问题讨论】:

  • 很遗憾不能使用嵌套集
  • 您可以做的是使用固定的树深度,例如 4,然后在查询中使用连接。我对深度为 4 的相邻树执行此操作,它应该比递归查询树更快。当然它看起来很丑,而且没有那么灵活。

标签: mysql performance tree hierarchical


【解决方案1】:

我解决了在 mysql 之外检索后代时间的问题(在将条目插入表之前)。

【讨论】:

  • 我知道你不能投票,但你能接受我的回答吗?我建议您使用固定深度,我认为这不是一个毫无价值的答案!谢谢!
  • 评论/答案不适用于上述情况,因为它不是固定深度树。链接文章中的树也不是固定深度树。深度是可变的。但是,如果它是固定深度树,我很可能会使用您的解决方案。我当然不打算忽视或抹黑你的回答。
  • 这不是一个好的答案,但我知道我不会再帮你了。
猜你喜欢
  • 1970-01-01
  • 2016-01-06
  • 2020-03-03
  • 2020-12-27
  • 1970-01-01
  • 2012-07-07
  • 1970-01-01
  • 2011-05-06
相关资源
最近更新 更多