【发布时间】: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
【问题讨论】: