这是mysql中的一张表。
子表:
id name parent_id
1 sub 0 //it means this the sub has not any parents.
2 sub1 1 //it means the parent is sub
3 sub2 1
4 sub3 3
5 sub4 4
6 sub5 0
7 sub6 6
如何给一个ID号并得到它的根父ID?
例如:
如果 ID=5 返回我 1
如果 ID=6 返回我 6
如果 ID=7 返回我 6
SELECT id from table sub_table
WHILE parent_id != 0
BEGIN
...?..
END
最佳答案
使用 PHP,您可以通过以下方式实现此目的:
$id = 5;$parent_id = 5; /* set default to values you want*/
while($parent_id != 0)
{
$sql = 'SELECT id,parent_id from sub_table where id = $parent_id ';
$rs= $mysqli->query($sql); /* fetch details */
$old_id = $id; /* this will save the last id in current iteration */
$parent_id = $rs['parent_id'];
$id = $rs['id'];
}
因此,一旦退出循环,您的结果将保存在 $old_id
关于mysql - 在sql中的嵌套表中返回父ID,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22033155/