![](/img/trans.png)
[英]Category>Sub category>Sub sub category>Sub sub subcategory>product 1
[英]Get parent names of category > sub category >sub sub category upto 5 level
表: 類別
-------------------------------------------
| 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
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 . " ");
}
}
// return the list of categories
return $output;
}
由於您最多有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
值。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.