选择递归进行搜索

时间:2014-02-06 22:06:13

标签: sql sql-server

我需要一个选项来搜索所有IDINTERNAL直到最后一个,请记住每个人都在同一个桌子上,每个记录都指向直接父母

我的表是:

idInternal              idFather
------------        |   ---------
79          |   0
80          |   79
83          |   79
89          |   79
119         |   79
120         |   79
81          |   80
82          |   80
84          |   83
85          |   83
117         |   83
98          |   89
99          |   89
121         |   89

我的旧查询:

SELECT * FROM MENU WHERE IdFather IN (
         SELECT IDINTERNAL FROM MENU WHERE IdFather IN (
         SELECT IDINTERNAL FROM MENU WHERE IdFather IN (
         SELECT IDINTERNAL FROM MENU WHERE IdFather IN (SELECT IDINTERNAL FROM MENU  WHERE IdFather = 79)
         )
         )
         )

请注意,表中的每条记录都是另一条记录的直接子记录

感谢提前

---这是查找id 79所有孩子的查询:

DECLARE @id INT     SET @id = 79;

WITH hierarchy AS (
  SELECT t.idInternal, t.idpadre
    FROM menu t
   WHERE t.idInternal = @id
 UNION ALL
 SELECT x.idInternal, x.idpadre
   FROM menu x
   JOIN hierarchy h ON h.idInternal = x.idpadre)
 SELECT h.idInternal
  FROM hierarchy h

1 个答案:

答案 0 :(得分:0)

如果您正在搜索菜单121,并且想要从121到顶部获得所有菜单,您可以执行以下操作:

declare @id int
set @id = 121

;with cte as
(
    select * from Menu where idInternal = @id
    union all

    select m.* 
    from Menu m
    inner join cte on m.idInternal = cte.idFather
)
select * from cte

要做一个自上而下的遍历,你会做这样的事情:

declare @id int
set @id = 79

;with cte AS (
    select idFather from Menu where idInternal = @id
), tree as (
    select m1.idFather, m1.idInternal
    from Menu m1
    inner join cte on m1.idFather = cte.idFather
    union all
    select m2.idFather, m2.idInternal
    from Menu m2
    inner join tree t ON m2.idFather = t.idInternal
)
select * from tree