获取类别>子类别>子子类别(最多5级)的父名称

时间:2018-11-14 10:00:58

标签: php mysql

表:类别

    -------------------------------------------
    | id | cat_name_en   | parent_id          |
    -------------------------------------------
    | 1  | level 1       |          0         |
    | 2  | level 2       |          1         |
    | 3  | Level 3       |          2         |
    | 4  | Level 4       |          3         |
    | 5  | level 5       |          4         |
    | 6  | test          |          1         |

在这里我需要将名称命名为

  

5级> 4级> 3级> 2级> 1级

在我的查询中,我最多只能看到2个名字

SELECT category,cat_id FROM ( SELECT CONCAT(p.cat_name_en, ' > ', c.cat_name_en) AS 'category',c.id as cat_id FROM categories c LEFT JOIN categories p ON c.parent_id = p.id ) s where cat_id = 5

2 个答案:

答案 0 :(得分:0)

function CategoryTree(&$output=null, $parent=0, $indent=null){
    // conection to the database
    $db = new PDO("mysql:host=localhost;dbname=tutorial", 'root', '');
    // select the categories that have on the parent column the value from $parent
    $r = $db->prepare("SELECT id, name FROM categories WHERE parent=:parentid");
    $r->execute(array(
        'parentid'  => $parent
    ));
    // show the categories one by one
    while($c = $r->fetch(PDO::FETCH_ASSOC)){
        $output .= '<option value=' . $c['id'] . '>' . $indent . $c['name'] . "</option>";
        if($c['id'] != $parent){
            // in case the current category's id is different that $parent
            // we call our function again with new parameters
            CategoryTree($output, $c['id'], $indent . "&nbsp;&nbsp;");
        }
    }
    // return the list of categories
    return $output;
}

答案 1 :(得分:0)

由于您最多拥有5个类别级别,因此可以根据需要为每个级别添加LEFT JOIN,以形成层次结构,

SELECT t1.id as cat_id,
CONCAT_WS(' > ', t1.cat_name_en, t2.cat_name_en, t3.cat_name_en, t4.cat_name_en, t5.cat_name_en)
FROM categories AS t1
LEFT JOIN categories AS t2 ON t2.id = t1.parent_id
LEFT JOIN categories AS t3 ON t3.id = t2.parent_id 
LEFT JOIN categories AS t4 ON t4.id = t3.parent_id
LEFT JOIN categories AS t5 ON t5.id = t4.parent_id
WHERE t1.id = 5;

CONCAT_WS不会合并NULL值。