【问题标题】:SQL Recursive Result to Find All Products within Category Hierarchy用于查找类别层次结构中所有产品的 SQL 递归结果
【发布时间】:2012-06-12 19:11:32
【问题描述】:

我想根据层次结构中的任何类别从 Product 表中返回所有产品。

例如,您可以按所有“福特”(类别 = 1)搜索产品,它会返回两个结果。

目前,此递归结果仅在产品表中与 CategoryHierarchy 表完全匹配时才返回产品。所以如果我说类别 = 4,它会起作用。

在产品表中,我有两辆福特野马。只是价格和描述不同(此处未显示),但它们的分类在产品类别方面是相同的。

[Product Table]
[ProductId] [ProductName] [CategoryId]
1       Ford Mustang 1     4
2       Ford Mustang 2     4
3       Buick Regal 3      12

每辆福特野马都有 1,2,3,4 的 CategoryHierarchy。如果 Sql 参数 minimumcategory 是 1 OR 2 OR 3 OR 4,那么这两个结果应该会显示出来。现在,它只有在它 = 4 时才有效。

[CategoryHierarchy]
[Id]    [parentId]  [categoryName]
1       0           Ford
2       1           Mustang
3       2           2010
4       3           Blue
10      0           Buick
11      10          Regal
12      11          1999

MS SQL 2008:

declare @lowestcategoryid int;

set @lowestcategoryid = 4;--returns the products but I need it to work if this var = 1,2,3 too

--recursive loop
with RecursiveResult( id, CategoryName, ProductName, parentId) as
(
select ch.Id, ch.categoryname, p.productname, ch.parentId
from CategoryHierarchy ch 
join product p on p.categoryId = ch.id
where ch.id = @lowestcategoryid

UNION ALL

select p.categoryId, ch.categoryName, p.productname, ch.parentId
from product p
join CategoryHierarchy ch on p.categoryId = ch.id
join RecursiveResult r on ch.parentId = r.Id 

)

select * from recursiveresult

【问题讨论】:

    标签: sql recursion


    【解决方案1】:

    我认为您想将递归部分(遍历 CategoryHierarchy 表)与 Product 的连接分开。从最低(或“最高”)类别开始并深入,最后加入 Product 上的那个集合...像这样:

    DECLARE @lowestcategoryid INT;
    
    SET @lowestcategoryid = 3;
    
    --recursive loop
    WITH RecursiveResult( id, CategoryName, parentId) AS
    (
    SELECT ch.Id, ch.categoryname, ch.parentId
    FROM CategoryHierarchy ch 
    WHERE ch.id = @lowestcategoryid
    
    UNION ALL
    
    SELECT ch.Id, ch.categoryname, ch.parentId
    FROM CategoryHierarchy ch 
        JOIN RecursiveResult r 
            ON r.Id = ch.ParentId
    
    )
    
    SELECT * 
    FROM recursiveresult r
        JOIN Product p
            ON p.CategoryId = r.Id
    

    【讨论】:

    • 不走运。对于最低类别 ID = 1 / 2 / 或 3,不返回任何结果。
    • 糟糕...我在 cte 的递归部分切换了 Id 和 ParentId。立即尝试。
    • 你是赢家。耶!谢谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-02-04
    • 2013-11-07
    • 2010-09-16
    • 2015-11-23
    • 2014-04-15
    • 2020-10-20
    • 1970-01-01
    相关资源
    最近更新 更多