帮助递归SQL

时间:2009-10-05 20:43:52

标签: sql recursion sql-server-2000

我有一个类似于此的类别表:

   uid | ParentLevel | ParentID | Name
   ------------------------------------
    1  |       0     |      0   |  foo
    2  |       1     |      1   |  blat
    3  |       1     |      1   |  baz
    4  |       2     |      3   |  blah
    5  |       0     |      0   |  bar

我正在尝试获得类似于此的输出:

1 | foo
2 | foo | blat
3 | foo | baz
4 | foo | baz | blah
5 | bar

等等。 CTE已经出来了,因为这是SQL 2000.我尝试过类似的东西,但似乎无法做到这一点:

SELECT     c1.uid, c1.Name, c2.Name AS Expr1, c3.Name AS Expr2
FROM         dbo.Categories AS c1 INNER JOIN
                  dbo.Categories AS c2 ON c1.uid = c2.ParentID INNER JOIN
                  dbo.Categories AS c3 ON c2.uid = c3.ParentID
WHERE     (c1.ParentLevel = 0) AND (c2.ParentLevel = 1) AND (c3.ParentLevel = 2)

如果存在并非总是如此的第三级,则这将仅返回记录。有没有办法做到这一点?

3 个答案:

答案 0 :(得分:3)

使用LEFT JOIN

SELECT     c1.uid, c1.Name, c2.Name AS Expr1, c3.Name AS Expr2
FROM         dbo.Categories AS c1 LEFT JOIN 
                  dbo.Categories AS c2 ON c1.uid = c2.ParentID LEFT JOIN 
                  dbo.Categories AS c3 ON c2.uid = c3.ParentID
WHERE     (c1.ParentLevel = 0) AND (c2.ParentLevel = 1) AND (c3.ParentLevel = 2)

答案 1 :(得分:1)

使用LEFT JOIN代替INNER JOIN并将条件从WHERE移至JOIN条件

SELECT      c1.uid, c1.Name, c2.Name AS Expr1, c3.Name AS Expr2
FROM        dbo.Categories AS c1 
LEFT JOIN   dbo.Categories AS c2 
        ON  c1.uid = c2.ParentID
        AND c2.ParentLevel = 1
LEFT JOIN   dbo.Categories AS c3 
        ON  c2.uid = c3.ParentID
        AND c3.ParentLevel = 2
WHERE       c1.ParentLevel = 0

答案 2 :(得分:1)

LEFT JOIN将帮助您获得预期的结果。 INNER JOIN仅合并与其他查询结果匹配的记录。