Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to query a tree structure table in MySQL in a single query, to any depth?

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.

like image 538
Cameron Booth Avatar asked Oct 04 '08 05:10

Cameron Booth


People also ask

Can we use like and in together in MySQL?

You can use LIKE with OR operator which works same as IN operator.


1 Answers

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/

like image 177
Dave Cheney Avatar answered Sep 20 '22 11:09

Dave Cheney