0

我有 2 张桌子:

类别

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 个级别

  • 第一类
    • 子类别 11
    • 子类别 111
    • 子类别 112
    • 子类别 113
  • 子类别 12
    • 子类别 121
    • 子类别 122
    • 子类别 123
    • 子类别 13
  • 第 2 类
  • 第 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...)时,如何查看此类别中的所有产品?

谢谢!

4

1 回答 1

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
于 2013-05-24T15:42:54.680 回答