mysql - 如何在mysql中显示Parent_id的parent_id直到parent_id为0

标签 mysql database relational-database

当我想在类别表上查询数据库时遇到问题,当我想显示 parent_idparent_id 直到 parent_id 是 0。

这是我的尝试 http://www.sqlfiddle.com/#!2/5dc009/1

这就是结果

enter image description here

我的目标是

group_id   |  parent_id   | cat_id | name | variant 

4          |  7           | 4      | Shampo With Conditioner | 1 
7          |  1           | 7      | Shampo Woman | null
1          |  0           | 1      | Hair Care | null

最佳答案

Go 递归:

function getRootId($id){
    // Select the parent_item which belongs to $id
    $query = "SELECT parent_id FROM table WHERE id=".$id." LIMIT 1";
    $result = mysqli_query($conn, $query);
    $fetch = $result->fetch_assoc();

    // If a parent found
    if($fetch['parent_id']!==0){
        $id = getRootId($fetch['parent_id']); // go up one level
    }
    return $id;
}

关于mysql - 如何在mysql中显示Parent_id的parent_id直到parent_id为0,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22035991/

相关文章:

database - 为什么关系数据库存在可扩展性问题?

javascript - 如何从 mySQL 中检查编辑页面的正确复选框?

mysql - 查询显示错误结果

python - 向mysql中插入数据

MySQL小写返回值或整个结果

mysql - 用户设置的数据库设计

php - 酒店预订 SQL 查询不起作用

mysql - 使用 'Index' 还是使用查询在相关数据库列之间创建连接更好?

php - MySQL 根据不同表中的值创建表

php - 多答案枚举的 SQL DB 设计