gpt4 book ai didi

php - 列出主类别和子类别的所有产品

转载 作者:行者123 更新时间:2023-11-30 01:37:05 27 4
gpt4 key购买 nike

我有 2 张 table :

类别

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

  • 类别 1
    • 子类别 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...)时,如何查看此类别中的所有产品?

谢谢!

最佳答案

如果层次结构的级别数已知或假定,您可以执行以下操作:

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

关于php - 列出主类别和子类别的所有产品,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16738034/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com