Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/database/10.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在mysql中显示父\u id的父\u id,直到父\u id为0_Mysql_Database_Relational Database - Fatal编程技术网

如何在mysql中显示父\u id的父\u id,直到父\u id为0

如何在mysql中显示父\u id的父\u id,直到父\u id为0,mysql,database,relational-database,Mysql,Database,Relational Database,当我想在我的分类表上查询我的数据库时,我遇到了一个问题,当我想显示parent_id的parent_id时,我被卡住了,直到parent_id为0为止 这是我的尝试 这就是结果 我的目标是 group_id | parent_id | cat_id | name | variant 4 | 7 | 4 | Shampo With Conditioner | 1 7 | 1 | 7

当我想在我的分类表上查询我的数据库时,我遇到了一个问题,当我想显示parent_id的parent_id时,我被卡住了,直到parent_id为0为止

这是我的尝试

这就是结果

我的目标是

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;
}
试试这个代码

 SELECT t1.id AS group_id, t1.parent AS parent_id, t2.id AS cat_id, t2.name AS name, 
 vr.id AS variant_id
 FROM categories_group AS t1
 LEFT JOIN categories AS t2 ON t2.id = t1.cat_id
 LEFT JOIN rev_variant_cat AS CRL ON CRL.cat_group_id = t1.id
 LEFT JOIN variant AS vr ON vr.id = CRL.variant_id
 WHERE t1.parent!=0 and vr.id>=1
 ORDER BY t1.id ASC 
 LIMIT 0 , 30
输出

GROUP_ID           PARENT_ID        CAT_ID          NAME              VARIANT_ID
4                     7               4           Shampo With Conditioner     1
4                     7               4           Shampo With Conditioner     2
7                     1               7           Shampo Woman                2

我想我应该在id_变体中使用vr.id,因为它将在另一端自定义