如何在sql中使用root父ID来选择父子项?

时间:2016-06-23 07:29:31

标签: sql sql-server

在表格下方: 我需要在没有recursion的情况下使用,但使用任何其他joinunion

Id  ParentId
1   0
2   1
3   2
4   2
5   4
6   5
7   6
8   7
9   8
N   N

不使用recursion使用任何其他join查询

2 个答案:

答案 0 :(得分:0)

DECLARE @Nvalue INT = 10

SELECT NUMBER AS ID,NUMBER-1 AS ParentID FROM (
SELECT DISTINCT NUMBER FROM master..spt_values WHERE number BETWEEN 1 AND @Nvalue
)T

答案 1 :(得分:0)

使用UNPIVOT和交叉连接的解决方案 无需像master..spt_values那样的系统表。

DECLARE @N INT = 12;
with Digits as (
  select n 
  from (select 0 as n0, 1 as n1, 2 as n2, 3 as n3, 4 as n4, 5 as n5, 6 as n6, 7 as n7, 8 as n8, 9 as n9) d
  unpivot (n for name in (n0,n1,n2,n3,n4,n5,n6,n7,n8,n9)) u
)
select Id, (Id - 1) as ParentId 
from (
  select (n10.n*10 + n1.n) as Id from Digits n10, Digits n1
) Ids
where Id between 1 and @N
order by Id;

虽然我个人仍然喜欢递归SQL。 例如:

DECLARE @N INT = 12;
WITH Numbers(Id, ParentId) AS (
  SELECT 1 Id, 0 as ParentId
  UNION ALL
  SELECT Id+1, Id as ParentId FROM Numbers WHERE Id < @N
)
SELECT * FROM Numbers
OPTION (maxrecursion 100);