[英]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): 我有一个表(例如名称为“ page”),其中每一行都是另一行的子级,如下所示(请参见HTML部分):
http://jsfiddle.net/Fuqrb/ http://jsfiddle.net/Fuqrb/
I want to find the topmost parent's id, by using a child's id. 我想通过使用孩子的ID来找到最顶层的父母的ID。 For example, we get a URL variable as the id of the bottommost child:
例如,我们获得一个URL变量作为最底层子代的ID:
http://www.website.com/page.php?p=6
Then we store the URL variable into a variable: 然后我们将URL变量存储到一个变量中:
$p = $_GET['p'];
To get the topmost parent's id, I have to use query function several times. 要获得最高的父代ID,我必须多次使用查询功能。 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. 这种方法是无效的,因为如果我得到另一个URL变量作为更高/更低级别的另一个孩子的ID,则此方法将无效。
How to get the topmost parent's id dynamically, regardless of the child's id? 不管孩子的ID如何如何动态获取最高的父母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);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.