日期:2014-05-17  浏览次数:20516 次

关于目录的查询语句
在数据库中有张表 这样的形式

其中第一列为ID 第二列存放名称 第三列是父级编号

我想查出一个目录的形式 利用第一列和第三列
我记得可以查 但是忘记怎么写了 
求各位大侠指点下 -_-

------解决方案--------------------
SQL code
; with cte as
(
select * from tb where type_id=1
union all
seelct b.* from cte as c,tb as b where c.peer_type_id=b.type_id
)
select * from cte

------解决方案--------------------
完全排列成树状结构应该不行。因为你不知道到底有几层目录结构。

大致可以使用如下的结构语句:
SQL code

with tb as
(
    select 0 as id, -1 as id2
    union all
    select 1 as id, 0 as id2
    union all
    select 382 as id, 0 as id2
    union all
    select 383 as id, 382 as id2
    union all
    select 385 as id, 0 as id2
    union all
    select 386 as id, 385 as id2
)
select tb.id, tb2.id from tb
left outer join tb tb2 on tb.id = tb2.id2
order by tb.id, tb2.id2

------解决方案--------------------
SQL code

-->这样么?
; with cte as
(
    select from 表 where TYPE_ID=0
    union all
    select b.* from cte c,表 b where b.PER_TYPE_ID=c.TYPE_ID
)
select * from cte