Get root path of a tree with pure MySQL

落花浮王杯 提交于 2020-01-16 05:00:47

问题


I want to get path from node to root of a tree. This is my tree for example:

id  |   name    |   parent_id
------------------------------
1   |   mike    |   0
2   |   danny   |   1
3   |   peter   |   1
4   |   clark   |   2
5   |   lily    |   1
6   |   stefan  |   3
7   |   simon   |   3
8   |   boby    |   1
9   |   john    |   4
10  |   elly    |   4

I write an algoritm with php and mysql but it is slowly

public function GetRootPath($a_id) {
    $root="";
    $results="";
    while(1==1){
        $result = DB::select("SELECT id, parent_id FROM users WHERE id=$a_id");
        if($result[0]->refr!=0) {
               if($root==""){
                   $root=$result[0]->parent_id;
               }
               else {
                   $root=$result[0]->parent_id.'.'.$root;
               } 
            $a_id=$result[0]->parent_id;
        }
       else {
           break;
       }
    }
    return $root;
}

How could this be written in pure MySQL? I'm not very aware with MySQL procedures and functions.


回答1:


I think stored procedures could work:

DELIMITER $$

DROP PROCEDURE IF EXISTS get_root;
CREATE PROCEDURE get_root(
   IN parentID INT,
   OUT rootID INT
)

BEGIN   
    SELECT parent_id FROM tree WHERE id = parentID INTO rootID;

    IF rootID = 0
        THEN SET rootID = parentID;
    ELSE
        CALL get_root(rootID, rootID);
    END IF;

END$$
DELIMITER ;

SET @@GLOBAL.max_sp_recursion_depth = 255;
SET @@session.max_sp_recursion_depth = 255; 

CALL get_root(4, @rootID);
SELECT @rootID;


来源:https://stackoverflow.com/questions/27579716/get-root-path-of-a-tree-with-pure-mysql

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!