私の質問は、次の記事 (テーブルと関数 hierarchy_connect_by_parent_eq_prior_id) http://explainextended.com/2009/03/17/hierarchical-queries-in-mysql/に基づいています。
テーブル t_hierarchy に 2 つの追加フィールド (id と親のほかに) typ1(char) と time(int) があると仮定します。フィールド typ1 は 2 つの値 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 と同じですが、グローバル変数の名前が異なるため、メイン クエリで使用されるものと干渉しません。
上記のソリューションは希望どおりに機能しますが、遅すぎます (特に大規模なデータセットを操作する場合)。より良い解決策を提供できますか、またはクエリを改善する方法を提案できますか? お時間とご協力いただきありがとうございます。