我有两张桌子:
类别
id - name - parent
1 - Category 1 - 0
2 - Category 2 - 0
3 - Category 3 - 0
4 - Category 4 - 0
5 - Subcategory 11 - 1
6 - Subcategory 111 - 5
7 - Subcategory 112 - 5
...
产品
id - name - category - description
1 - Name - 5 - Description
在类别表中,我有3个级别
我从子类别中选择产品:
mysql_query("SELECT *, products.name AS p_name, categories.name AS c_name
FROM products
INNER JOIN categories ON categories.id = products.category
WHERE categories.id = '". $_GET['items'] ."'
GROUP BY products.id DESC");
产品属于第三级别类别(子类别111,子类别112,子类别113,子类别121 ...)
当我访问父类别或主要类别(类别1,类别2,子类别11,子类别12 ...)时,如何查看此类别中的所有产品?
谢谢!
答案 0 :(得分:0)
如果知道或假设等级的级别数,您可以执行以下操作:
Select Root.name
, Level1.name As Level1Category
, Level2.name As Level2Category
From Category As Root
Left Join Category As Level1
On Level1.parent = Root.id
Left Join Category As Level2
On Level2.parent = Level1.id
Where Root.parent = 0
Order By Root.name, Level1.name, Level2.name
然后查看您只需将产品加入到层次结构的任何级别的产品:
Select Root.name
, Level1.name As Level1Category
, Level2.name As Level2Category
, P.name As ProductName
From Category As Root
Left Join Category As Level1
On Level1.parent = Root.id
Left Join Category As Level2
On Level2.parent = Level1.id
Join Products As P
On P.category = Root.id
Or P.category = Level1.id
Or P.category = Level2.id
Where Root.parent = 0
Order By Root.name, Level1.name, Level2.name, P.name