我有一个item_categories
具有以下架构的 MySQL 表(名称:):
id INT(11) PRIMARY KEY, AUTO INCREMENT
category_name VARCHAR(100) NOT NULL
parent_id INT(11) NOT NULL, Default 0
样本数据:
id category_name parent_id
=============================
1 Fruit 0
2 Animal 0
3 Furniture 0
4 Apple 1
5 Orange 1
6 Cat 2
7 Dog 2
8 Black Dog 7
9 White Dog 7
如果我必须列出类别及其父类别,我必须多次循环访问数据库表。
我的问题是:如何简化循环任务?
当前循环任务查询:
// 1st query
$sql = "SELECT * FROM item_categories";
$rs = $db->query($sql);
while($row = $db->result($rs)) {
if((int)$row['parent_id'] === 0) {
// it is parent
echo $row['category_name'] . PHP_EOL;
} else {
$category = $row['category_name'];
// it has parent
$sql = "SELECT * FROM item_categories WHERE id=" . $row['parent_id'];
$rs2 = $db->query($sql);
$row2 = $db->result($rs);
$parent_id = (int)$row2['parent_id'];
while($parent_id != 0) {
$sql = "SELECT * FROM item_categories WHERE id=" . $row['parent_id'];
$rs2 = $db->query($sql);
$row2 = $db->result($rs);
$parent_id = (int)$row2['parent_id'];
$category = $row2['category_name'] . ' > ' . $category;
}
echo $category;
}
}
这将输出:
Fruit
Animal
Furniture
Fruit > Apple
Fruit > Orange
Animal > Cat
Animal > Dog
Animal > Dog > Black Dog
Animal > Dog > White Dog