SQL查询树表 [英] Sql query for tree table

查看:105
本文介绍了SQL查询树表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一张带有树形结构的桌子:

I have a table with tree structure:

id parentId name
----------------
1  0        Category1
2  0        Category2
3  1        Category3
4  2        Category4
5  1        Category5
6  2        Category6
7  3        Category7

在sql query resut中,我需要一个像这样的表:

In sql query resut I need a table like:

id parentId level name
----------------------
1  0        0     Category1
3  1        1     Category3
7  3        2     Category7
5  1        1     Category5
2  0        0     Category2
4  2        1     Category4
6  2        1     Category6

谁可以帮助我编写ms-sql查询? 谢谢!

Who can help me to write ms-sql query? Thanks!

推荐答案

扩展a_horse_with_no_name的答案,这显示了如何使用SQL Server的

Expanding on a_horse_with_no_name's answer, this show how to use SQL Server's implementation of recursive CTE (recursive single-record cross apply) in combination with row_number() to produce the exact output in the question.

declare @t table(id int,parentId int,name varchar(20))
insert @t select 1,  0        ,'Category1'
insert @t select 2,  0,        'Category2'
insert @t select 3,  1,        'Category3'
insert @t select 4 , 2,        'Category4'
insert @t select 5 , 1,        'Category5'
insert @t select 6 , 2,        'Category6'
insert @t select 7 , 3,        'Category7'
;

WITH tree (id, parentid, level, name, rn) as 
(
   SELECT id, parentid, 0 as level, name,
       convert(varchar(max),right(row_number() over (order by id),10)) rn
   FROM @t
   WHERE parentid = 0

   UNION ALL

   SELECT c2.id, c2.parentid, tree.level + 1, c2.name,
       rn + '/' + convert(varchar(max),right(row_number() over (order by tree.id),10))
   FROM @t c2 
     INNER JOIN tree ON tree.id = c2.parentid
)
SELECT *
FROM tree
order by RN

说实话,使用ID本身来生成树路径"是可行的,因为我们直接通过id进行排序,但是我认为我会使用row_number()函数.

这篇关于SQL查询树表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆