我有一个名为“Categories”的数据库设置,其中可以创建类别并设置父类。 Parent列下的父类别将设置为“0”,其中id将用于设置其子类别。
嵌套类别可以是4个类别:
Parent >> Subcategory >> subcategory >> subcategory
我的查询设置如下:
SELECT *,
cat_a.id AS A_ID, cat_a.Title AS A_Title, cat_a.Parent AS A_Parent,
cat_b.id AS B_ID, cat_b.Title AS B_Title, cat_b.Parent AS B_Parent,
cat_c.id AS C_ID, cat_c.Title AS C_Title, cat_c.Parent AS C_Parent,
cat_d.id AS D_ID, cat_d.Title AS D_Title, cat_d.Parent AS D_Parent
FROM Categories AS cat_a
LEFT JOIN Categories AS cat_b
ON cat_a.Parent = cat_b.id
LEFT JOIN Categories AS cat_c
ON cat_b.Parent = cat_c.id
LEFT JOIN Categories AS cat_d
ON cat_c.Parent = cat_d.id
WHERE cat_a.Username='$UserID'
GROUP BY cat_a.id
这会根据需要显示信息,但排序不正确。 我希望嵌套显示,所以每个子类与父项将直接在它下面循环,如下所示:
Universe
-> Milky Way
--> Planets
---> Earth
---> Mars
--> Moons
---> Titan
---> Europa
-> Andromeda
--> Unknown Planets
---> Planet X
等。
谢谢你的时间!
答案 0 :(得分:1)
如果我正确理解数据结构,您就不需要group by
。相反,使用:
order by cat_a.id, cat_b.id, cat_c.id, cat_d.id