简体   繁体   中英

Get The Topmost Parent's ID, Regardless of The Child's ID

I have a table (eg the name is "page"), where each row is a child of another row, like below (see the HTML section):

http://jsfiddle.net/Fuqrb/

I want to find the topmost parent's id, by using a child's id. For example, we get a URL variable as the id of the bottommost child:

http://www.website.com/page.php?p=6

Then we store the URL variable into a variable:

$p = $_GET['p'];

To get the topmost parent's id, I have to use query function several times. For example:

if($result = $mysqli->query("SELECT * FROM page WHERE id='$p' LIMIT 1"))
{
    while($row = $result->fetch_array())
    {
        $parent = $row["parent"];
    }
}

if($result = $mysqli->query("SELECT * FROM page WHERE id='$parent' LIMIT 1"))
{
    while($row = $result->fetch_array())
    {
        $parent1 = $row["parent"];
    }
}

if($result = $mysqli->query("SELECT * FROM page WHERE id='$parent1' LIMIT 1"))
{
    while($row = $result->fetch_array())
    {
        $parent2 = $row["parent"];
    }
}

if($result = $mysqli->query("SELECT * FROM page WHERE id='$parent2' LIMIT 1"))
{
    while($row = $result->fetch_array())
    {
        $id = $row["id"];
    }
}

This way is ineffective, because if I got another URL variable as the id of another child of the higher/ lower level, this will not work.

How to get the topmost parent's id dynamically, regardless of the child's id?

DELIMITER $$

CREATE FUNCTION `fnGetRootParent`(
    page INT
) RETURNS int(11)
    READS SQL DATA
    DETERMINISTIC
BEGIN
    DECLARE _parent INT;
    DECLARE _result INT;

    SET _parent = page;

    my_loop: LOOP
        SELECT 
             p.id
            ,p.parent
        INTO 
             _result
            ,_parent
        FROM page p
        WHERE id = _parent;

        IF (_parent = 0) OR (_parent = _result) THEN
            LEAVE my_loop;
        END IF;
    END LOOP my_loop;

    RETURN _result;
END

SELECT fnGetRootParent(213);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM