我使用递归查询来识别给定category-id的所有相关子类别。
WITH parent AS ( SELECT ParentId, Title, Id
FROM [CocoDb].[dbo].[Categories]
WHERE Id = @CategoryId),tree AS
(
SELECT x.ParentId, x.Id, x.Title
FROM [CocoDb].[dbo].[Categories] x
INNER JOIN parent ON x.ParentId = parent.Id
UNION ALL
SELECT y.ParentId, y.Id, y.Title
FROM [CocoDb].[dbo].[Categories] y
INNER JOIN tree t ON y.ParentId = t.Id
)
SELECT * FROM Tree
我的表是:
Categories (ID INT PRIMARY KEY, ParentId INT, Title VARCHAR(MAX))
SQL Server问题:我可以查询返回所有类别吗?
例如:
现在,如果我要求Steven King(Id 3),我将获得所有相关类别,例如书籍和恐怖片。
是否可以使用递归SQL查询?
祝你好运
答案 0 :(得分:2)
测试数据
DECLARE @Categories TABLE(ID INT PRIMARY KEY, ParentId INT, Title VARCHAR(MAX))
INSERT INTO @Categories
VALUES (1, 0, 'Books'),(2, 1, 'Horro'),(3, 2, 'Steven King')
,(4, 3, 'Value 4'),(5, 4, 'Value 5')
<强>查询强>
;WITH ParentCte
AS
(
SELECT p.ID ,p.ParentId ,p.Title
FROM @Categories p
WHERE p.Title = 'Steven King'
UNION ALL
SELECT c.ID ,c.ParentId,c.Title
FROM ParentCte cte INNER JOIN @Categories c
ON c.ID = cte.ParentId
)
SELECT *
FROM ParentCte m
结果集
╔════╦══════════╦═════════════╗
║ ID ║ ParentId ║ Title ║
╠════╬══════════╬═════════════╣
║ 3 ║ 2 ║ Steven King ║
║ 2 ║ 1 ║ Horro ║
║ 1 ║ 0 ║ Books ║
╚════╩══════════╩═════════════╝