mysql - 在sql中的嵌套表中返回父ID

标签 mysql sql

这是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/

相关文章:

mysql - 如何检查表中单行SQL中的任何值是否为Null

MySQLDump 无法将数据导入亚马逊 RDS

mysql - 如何对此查询进行正确的内连接?

sql - 在 SQL 中,在 where 语句中返回值时 "IS"和 "="之间有区别吗?

html - URL 未拉取索引页

mysql - 添加子查询

mysql - 如何避免 mysql DB 上的高负载?

mysql 一张表中的不同时间间隔

MySql Join with Sum 返回错误的输出

java - Hibernate 对 group by 的查询