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?

Answers


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);


Need Your Help

ubuntu and libcap (capabilities) undefined reference

c ubuntu undefined-reference capability

I'm trying to compile the following minimal C code on ubuntu 10.10:

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.