递归 SQL 帮助
我有一个与此类似的类别表:
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)
只有在存在第三个级别(并不总是如此)时,才会返回记录。有办法做到这一点吗?
I have a category table similar to this:
uid | ParentLevel | ParentID | Name
------------------------------------
1 | 0 | 0 | foo
2 | 1 | 1 | blat
3 | 1 | 1 | baz
4 | 2 | 3 | blah
5 | 0 | 0 | bar
I am trying to get output similar to this:
1 | foo
2 | foo | blat
3 | foo | baz
4 | foo | baz | blah
5 | bar
And so on. CTE's are out as this is SQL 2000. I have tried something like this, but can't seem to get it quite right:
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)
This would only return records if there is a third level which isn't always true. Is there a way to do this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
使用
LEFT JOIN
Use
LEFT JOIN
使用
LEFT JOIN
而不是INNER JOIN
并将级别上的条件从WHERE
移动到JOIN
条件Use
LEFT JOIN
instead ofINNER JOIN
and move conditions on level fromWHERE
toJOIN
conditionsLEFT JOIN 将帮助您获得预期的结果。 INNER JOIN 仅合并与其他查询结果匹配的记录。
LEFT JOIN will help you to get the expected result. INNER JOIN merges only the records which matches from other query result.