可以在单个查询中查询MySQL中的树结构表,以便任何深度? [英] Is it possible to query a tree structure table in MySQL in a single query, to any depth?
问题描述
更具体地说,给定一个树结构化表(id,data,data,parent_id)和表中的一行,是否可以获得所有后代/孙子/等等),或者所有的祖先(父母/祖父母/等等),不知道它会走多远还是要去,使用单个查询?
或者正在使用某种递归要求,我不断更深入地查询,直到没有新的结果?
具体来说,我使用的是Ruby和Rails,但是猜测这不是很相关。
是的,这是可能的,这是一个被称为修改预订树遍历,这里最好描述
此处提供了一个工作示例(PHP)
http://www.sitepoint.com/article/hierarchical-data-database/2/
I'm thinking the answer is no, but I'd love it it anybody had any insight into how to crawl a tree structure to any depth in SQL (MySQL), but with a single query
More specifically, given a tree structured table (id, data, data, parent_id), and one row in the table, is it possible to get all descendants (child/grandchild/etc), or for that matter all ancestors (parent/grandparent/etc) without knowing how far down or up it will go, using a single query?
Or is using some kind of recursion require, where I keep querying deeper until there are no new results?
Specifically, I'm using Ruby and Rails, but I'm guessing that's not very relevant.
Yes, this is possible, it's a called a Modified Preorder Tree Traversal, as best described here
Joe Celko's Trees and Hierarchies in SQL for Smarties
A working example (in PHP) is provided here
http://www.sitepoint.com/article/hierarchical-data-database/2/
这篇关于可以在单个查询中查询MySQL中的树结构表,以便任何深度?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!