可以在单个查询中查询MySQL中的树结构表,以便任何深度? [英] Is it possible to query a tree structure table in MySQL in a single query, to any depth?

查看:164
本文介绍了可以在单个查询中查询MySQL中的树结构表,以便任何深度?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我认为答案是否定的,但我很乐意,任何人都有洞察到如何在SQL(MySQL)中爬行树结构到任何深度,但使用单个查询



更具体地说,给定一个树结构化表(id,data,data,parent_id)和表中的一行,是否可以获得所有后代/孙子/等等),或者所有的祖先(父母/祖父母/等等),不知道它会走多远还是要去,使用单个查询?



或者正在使用某种递归要求,我不断更深入地查询,直到没有新的结果?



具体来说,我使用的是Ruby和Rails,但是猜测这不是很相关。

解决方案

是的,这是可能的,这是一个被称为修改预订树遍历,这里最好描述



Joe Celko的SQL树和层次结构Smarties



此处提供了一个工作示例(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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆