我有一个存储类别和子类别的表(自联接)
The table structure is like this:
-CategoryId
-CategoryName
-ParentCategoryId
如何在sql查询中找到一个类别的第n个孩子/孩子
我有一个存储类别和子类别的表(自联接)
The table structure is like this:
-CategoryId
-CategoryName
-ParentCategoryId
如何在sql查询中找到一个类别的第n个孩子/孩子
这样的事情怎么样
DECLARE @Categories TABLE(
CategoryId INT,
CategoryName VARCHAR(20),
ParentCategoryId INT
)
INSERT INTO @Categories SELECT 1, '1',NULL
INSERT INTO @Categories SELECT 2, '2',NULL
INSERT INTO @Categories SELECT 3, '1.3',1
INSERT INTO @Categories SELECT 4, '1.4',1
INSERT INTO @Categories SELECT 5, '1.3.5',3
INSERT INTO @Categories SELECT 6, '1.3.6',3
INSERT INTO @Categories SELECT 7, '1.3.6.7',6
INSERT INTO @Categories SELECT 8, '1.4.8',4
DECLARE @CatID INT,
@NthLevel INT
SELECT @CatID = 1,
@NthLevel = 2
;WITH Vals AS (
SELECT *,
1 AS CatLevel
FROM @Categories c
WHERE CategoryId IS NULL
UNION ALL
SELECT c.*,
CatLevel + 1 AS CatLevel
FROM Vals v INNER JOIN
@Categories c ON c.ParentCategoryId = v.CategoryID
)
SELECT *
FROM Vals
WHERE CatLevel = @NthLevel
这将递归地构建树结构,并将其限制在您正在寻找的树级别。
SELECT ParentCategoryId,
, CategoryId AS [n-th child]
FROM (
SELECT CategoryId
, ParentCategoryId
, ROW_NUMBER() OVER (PARTITION BY ParentCategoryId ORDER BY CategoryId) as ChildNumber
FROM Categories
) p
WHERE ChildNumber = %N
要查找category 的N
第 th 个子项,按 CategoryId 排序M
:
select *
from (
select row_number() over (order by c.CategoryId) as rn
, c.*
from Categories p
join Categories c
on p.CategoryId = c.ParentCategoryId
where p.CategoryId = M
)
where rn = N