Sql问题:获取父行,然后获取子行
idparent_id
1 0
2 0
3 2
4 0
5 1
6 0
我需要一个查询,该查询将返回父行(parent_id = 0),后跟其子行
第一个父级
第一个父级的所有子级
第二个父级第二个父级
的所有子级第三
个父级
第四个父级
预期结果:按 id
id Parent_id
排序1 0(第一个父级)
5 1(第一个父级的所有子级)
2 0 第二个父级
3 2(第二个父级的所有子级)
4 0 第三个父级
6 0 第四个父级
我可以使用并集所有孩子都跟随父母 但这首先给了我父母,然后是孩子。 我需要父母,并且立即需要它的孩子。
有人可以帮忙吗?
id parent_id
1 0
2 0
3 2
4 0
5 1
6 0
I need a query that will return parent rows (parent_id=0) followed by its child rows
first parent
all children of first parent
second parent
all children of second parent
third parent
fourth parent
Expected result: ordered by id
id parent_id
1 0 (first parent)
5 1 (all children of first parent)
2 0 second parent
3 2 (all children of second parent)
4 0 third parent
6 0 fourth parent
I can use union of parents followed by all childs
But that gives me parents first then the children.
I need parent and immediately its children.
Anyone can help?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
这是一个使用带有 order by 子句的联合的示例解决方案(尽管它不适用于深度嵌套)。
Here is an example solution using a union with an order by clause (It wont work for deep nesting though).
据我所知,如果您存储的只是父 ID,则无法使用单个 SQL 语句来完成此操作。如果您需要快速检索数据树,则必须考虑存储前序遍历。这比听起来更容易,并且在这里有很好的描述:http://articles.sitepoint。 com/article/hierarchical-data-database
As far as i know, you can't do this with a single SQL statement if all you're storing is the parent id. If you need to retrieve the tree of data quickly, you'll have to consider storing a pre-order traversal. It's easier than it sounds and it's very well described here: http://articles.sitepoint.com/article/hierarchical-data-database
为此,您可以使用递归 CTE:
请注意,如果任何 ID 的值大于 999,则此特定版本将中断;如果级别超过 12,则该版本将中断。如果您担心这一点,则需要调整各个位置的零数量。
可能有更好的方法,但这个有效。
You'd use a recursive CTE for this:
Note that this particular version will break if any ID has a value greater than 999, and it will break if you have more than 12 levels. If this is a concern to you, you need to adjust the number of zeroes in the various places.
There might be better ways, but this one works.