Sql server 如何在sql中从上到下获取产品的层次分类

Sql server 如何在sql中从上到下获取产品的层次分类,sql-server,categories,hierarchy,recursive-query,Sql Server,Categories,Hierarchy,Recursive Query,我使用parentid逻辑保存产品类别。我需要将所有产品归入一个类别,但从上到下的层次结构。例如,我有以下表格: 产品类别 id CategoryID ProductID 1 4 1 2 5 2 3 6 3 4 8 4 5 8 5 6 9 5 7 9 2 ID CategoryName

我使用parentid逻辑保存产品类别。我需要将所有产品归入一个类别,但从上到下的层次结构。例如,我有以下表格:

产品类别

id   CategoryID   ProductID
1    4            1
2    5            2
3    6            3
4    8            4
5    8            5
6    9            5
7    9            2
ID     CategoryName    ParentID
1      Kids            NULL
2      Accesories      1
3      Shoes           2
4      Flat Shoes      3
5      Leather Sandals 4
6      Sneakers        3
7      Clothing        1
8      T-Shirts        7
9      Bestsellers     1
类别

id   CategoryID   ProductID
1    4            1
2    5            2
3    6            3
4    8            4
5    8            5
6    9            5
7    9            2
ID     CategoryName    ParentID
1      Kids            NULL
2      Accesories      1
3      Shoes           2
4      Flat Shoes      3
5      Leather Sandals 4
6      Sneakers        3
7      Clothing        1
8      T-Shirts        7
9      Bestsellers     1
产品

ID   ProductName
1    White Espadrilles
2    Tan Leather Sandals
3    Beige Sneakers
4    Linen T-Shirt
5    Cotton T-Shirt
我使用以下Sql递归查询:

with CTE as
(
select c.ID,c.ParentID,c.CategoryName,p.ProductName 
from Categories c
join ProductCategories pc
  on pc.CategoryID=c.ID
join Products p
  on pc.ProductID=p.ID
where c.ID = 5 --start id

union all
select ce.ID,ce.ParentID,ce.CategoryName,p.ProductName 
from Categories ce
join ProductCategories pc
  on pc.CategoryID=ce.ID
join Products p
  on pc.ProductID=p.ID
join CTE
  on ce.ID=CTE.ParentID 
)
select * from CTE
上述查询返回给定CategoryID=5的以下结果:

ID     ParentID     CategoryName      ProductName
5      4            Leather Sandals   Tan Leather Sandals
4      3            Flat Shoes        White Espadrilles
如果categoryID=1或2,则不会出现记录

我没有直接针对附件类别的产品,但我有针对其子类别的产品,所以我应该从上到下获取该类别下的所有产品


我怎样才能做到这一点呢?

你没有说你在使用哪个数据库,所以我会给你一个通用的解决方案

可以使用递归CTE生成类别列表,其中包括起始类别及其所有子类别(在多个级别中)。然后,简单联接将完成其余的工作,正如您已经尝试过的那样

这里有一个例子。根据需要对特定数据库进行调整:

with
categories_subtree as (
  select id, categoryname, parentid
  from categories 
  where id = 5 -- starting category
  union all
  select c.id, c.categoryname, c.parentid
  from categories_subtree s
  join categories c on c.parentid = s.id
)
select
  p.id,
  c.parentid
  c.categoryname,
  p.productname
from categories_subtree c
join productcategories pc on pc.categoryid = c.id
join products p on p.id = pc.productid

首先使用递归CTE只探索类别,然后加入产品。其他类别中缺少的产品会破坏递归。
White Espadrilles
是错误的,因为它不属于类别
5
。“是吗?”船长怀特·埃斯帕德里尔斯的分类是4。我使用Microsoft Sql数据库谢谢!有没有办法在您的解决方案中使用
左外联接
?或者我应该找到另一种方法吗?是的,您可以使用
LEFT JOIN