作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
假设您必须遵循以下表格,其中销售由产品组成,并且产品可以放在多个类别中。其中类别具有如下层次结构:
Man
Shoes
Sport
Casual
Watches
Women
Shoes
Sport
Casual
Watches
表格:
Sale:
id name
1 Sale1
Product:
id saleidfk name
1 1 a
2 1 b
3 1 c
4 1 d
5 1 e
ProductCategory :
productid categoryid
1 3
2 3
3 4
4 5
5 10
Category:
id ParentCategoryIdFk name
1 null Men
2 1 Shoes
3 2 Sport
4 2 Casual
5 1 Watches
6 null Women
7 6 Shoes
8 7 Sport
9 7 Casual
10 6 Watches
题:
Men
Shoes
Sport
Casual
Watches
Women
Watches
最佳答案
尝试这样的事情 - 获得类别的分层列表的基本 CTE 类似于:
WITH Categories AS
(
SELECT Cat.ID, Cat.NAME, Cat.ParentCategoryID, CAST('none' AS VARCHAR(50)) AS 'ParentCategory', 1 AS 'Level'
FROM dbo.MBCategory Cat
WHERE Cat.ParentCategoryID IS NULL
UNION ALL
SELECT Cat.ID, Cat.NAME, Cat.ParentCategoryID, c2.NAME AS 'ParentCategory', LEVEL + 1
FROM dbo.MBCategory CAT
INNER JOIN Categories c2 ON cat.ParentCategoryID = c2.ID
)
SELECT * FROM Categories
WITH Categories AS
(
SELECT Cat.ID, Cat.NAME, Cat.ParentCategoryID, CAST('none' AS VARCHAR(50)) AS 'ParentCategory', 1 AS 'Level'
FROM dbo.MBCategory Cat
WHERE Cat.ParentCategoryID IS NULL
UNION ALL
SELECT Cat.ID, Cat.NAME, Cat.ParentCategoryID, c2.NAME AS 'ParentCategory', LEVEL + 1
FROM dbo.MBCategory CAT
INNER JOIN Categories c2 ON cat.ParentCategoryID = c2.ID
)
SELECT DISTINCT s.*, c.*
FROM dbo.Sale s
INNER JOIN dbo.Product p ON p.SaleID = s.ID
INNER JOIN dbo.ProductCategory pc ON p.ID = pc.ProductID
INNER JOIN Categories c ON pc.CategoryID = c.ID
ORDER BY Level
ID Name CatID CatName ParentCatID ParentCatName Level
1 Sale1 5 Watches 1 Men 2
1 Sale1 10 Watches 6 Women 2
1 Sale1 3 Sport 2 Shoes 3
1 Sale1 3 Sport 2 Shoes 3
1 Sale1 4 Casual 2 Shoes 3
关于SQL:使用公用表表达式递归获取父记录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2618102/
我是一名优秀的程序员,十分优秀!