如何在mysql中显示parent_id为0之前显示parent_id的parent_id

时间:2014-02-26 08:43:54

标签: mysql database relational-database

当我想在我的类别表上查询我的数据库时出现问题,当parent_id显示parent_id parent_id时,我感到困惑。

这是我的尝试 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

2 个答案:

答案 0 :(得分:0)

去递归:

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;
}

答案 1 :(得分:0)

试试此代码

 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