id | title | path | level | paths |
---|---|---|---|---|
1 | 衣物 | 0 | 0 | 0,1 |
2 | 上衣 | 0,1 | 1 | 0,1,2 |
7 | 衬衫 | 0,1,2 | 2 | 0,1,2,7 |
3 | 裤子 | 0,1 | 1 | 0,1,3 |
4 | 西裤 | 0,1,3 | 2 | 0,1,3,4 |
5 | 长西裤 | 0,1,3,4 | 3 | 0,1,3,4,5 |
6 | 短西裤 | 0,1,3,4 | 3 | 0,1,3,4,6 |
其中,path表示父级id列表。例如西裤的0,1,3就表示衣物 > 裤子
实现面包屑时只要取出path字段的值,然后用,分割,得到id列表
再用where id in (1,3)即可
需要显示所有分类并表示层级时,使用下面的SQL:
SELECT *,concat(path,',',id) AS paths FROM menu ORDER BY paths
懒加载
SELECT
dept.id,
dept.path,
dept.paths,
dept.title AS title,
dept.id AS "value",
dept.id AS "key",
(
SELECT
CASE WHEN count(1) > 0 THEN 1 ELSE 0 END
FROM
menu
WHERE
parent_id = dept.id and is_deleted = 0
) AS "has_children"
FROM
menu dept
WHERE
dept.path = 1 AND dept.is_deleted = 0
ORDER BY dept.sort