資料表結構設計
CREATE TABLE `category` (
`id` INT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
`pid` INT UNSIGNED DEFAULT 0 COMMENT '父分類 ID,0 為頂層',
`name` VARCHAR(100) NOT NULL COMMENT '分類名稱',
`sort` INT DEFAULT 0 COMMENT '排序權重',
`status` TINYINT DEFAULT 1 COMMENT '1=啟用 0=停用'
);
資料範例
id | pid | name
---|-----|-----
1 | 0 | 電子產品
2 | 1 | 手機
3 | 1 | 筆電
4 | 2 | iPhone
5 | 2 | Android
6 | 0 | 服飾
7 | 6 | 上衣
核心邏輯:一次查詢 + PHP 組裝樹狀結構(推薦)
<?php
function buildCategoryTree($categories, $pid = 0, $level = 0) {
$tree = [];
foreach ($categories as $cat) {
if ($cat['pid'] == $pid) {
$cat['level'] = $level;
$children = buildCategoryTree($categories, $cat['id'], $level + 1);
if ($children) $cat['children'] = $children;
$tree[] = $cat;
}
}
return $tree;
}
function renderCategoryTree($tree) {
$html = '<ul class="category-tree">';
foreach ($tree as $cat) {
$html .= '<li>';
$html .= '<span class="level-' . $cat['level'] . '">' . htmlspecialchars($cat['name']) . '</span>';
if (!empty($cat['children'])) {
$html .= renderCategoryTree($cat['children']);
}
$html .= '</li>';
}
$html .= '</ul>';
return $html;
}
// 使用範例
$pdo = new PDO('mysql:host=localhost;dbname=test', 'root', 'pass');
$stmt = $pdo->query('SELECT * FROM category WHERE status=1 ORDER BY sort, id');
$allCats = $stmt->fetchAll(PDO::FETCH_ASSOC);
$tree = buildCategoryTree($allCats);
echo renderCategoryTree($tree);
?>
替代方案:遞迴查詢(資料量小時可用)
<?php
// 原文範例風格:巢狀查詢(不推薦大量資料)
function getChildren($parentId) {
global $db;
$sql = "SELECT * FROM category WHERE pid = ? AND status = 1 ORDER BY sort";
return $db->query($sql, [$parentId])->fetchAll();
}
function renderRecursive($parentId = 0, $level = 0) {
$children = getChildren($parentId);
if (!$children) return '';
$html = '<ul>';
foreach ($children as $cat) {
$html .= '<li>' . str_repeat('—', $level) . htmlspecialchars($cat['name']);
$html .= renderRecursive($cat['id'], $level + 1);
$html .= '</li>';
}
$html .= '</ul>';
return $html;
}
echo renderRecursive();
?>
效能比較與選擇建議
| 方案 | 查詢次數 | 適用資料量 | 優點 | 缺點 |
| 一次查詢 + PHP 組裝 | 1 | < 10,000 筆 | 極快、單次查詢、易快取 | 記憶體佔用隨資料增長 |
| 遞迴查詢 | N(層級數) | < 1,000 筆 | 程式碼簡單、記憶體少 | N+1 查詢問題、資料量大極慢 |
| 遞迴 CTE (MySQL 8.0+) | 1 | 大量資料 | 資料庫層級完成、支援深度查詢 | 需 MySQL 8.0+、語法較複雜 |
| Closure Table | 1 | 超大量、頻繁移動節點 | 查詢極快、支援任意深度祖先/後代 | 寫入複雜、儲存空間大 |
MySQL 8.0 遞迴 CTE 範例
<?php
// 取得某分類的所有後代(含自身)
$sql = "
WITH RECURSIVE cat_tree AS (
SELECT id, pid, name, 0 AS depth FROM category WHERE id = ?
UNION ALL
SELECT c.id, c.pid, c.name, ct.depth + 1
FROM category c
INNER JOIN cat_tree ct ON c.pid = ct.id
)
SELECT * FROM cat_tree ORDER BY depth, sort;
";
$stmt = $pdo->prepare($sql);
$stmt->execute([$targetId]);
$descendants = $stmt->fetchAll(PDO::FETCH_ASSOC);
?>
前端呈現建議
- 使用 CSS `padding-left: calc(var(--level) * 20px)` 控制縮排。
- 配合 `
/` 原生摺疊效果。
- 大量資料採用虛擬滾動或懶加載(AJAX 載入子節點)。