我的问题基于以下文章(表和函数 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 相同,但它具有不同命名的全局变量,因此不会干扰主查询中使用的变量。
上述解决方案按预期工作,但速度太慢(尤其是在处理大型数据集时)。您能否提供更好的解决方案或建议如何改进查询?提前感谢您的时间和帮助!