Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Connect By Prior Equivalent for MySQL

All,

I have three fields in a table that define a parent child relationship present in a MySQL database version 5.0 . The table name is tb_Tree and it has the following data:

Table Name: tb_Tree

Id | ParentId | Name
--------------------
1  | 0        | Fruits
2  | 0        | Vegetables
3  | 1        | Apple
4  | 1        | Orange
5  | 2        | Cabbage
6  | 2        | Eggplant

How do I write a Query to get all the children if a ParentId is specified. Note that the table entries given are just sample data and they can have many more rows. Oracle has a "CONNECT BY PRIOR" clause, but I didn't find anything similar for MySQL. Can anyone please advise?

Thanks

like image 939
Jake Avatar asked Oct 03 '11 04:10

Jake


People also ask

What is connect by Prior in SQL?

"connect by" -- describes how to walk from the parent nodes above to their children and their childrens children. Easiest to use an example on emp. If we start with "where mgr is NULL", we generate the set of employees that have no mgr (they are the top of the tree). If we. CONNECT BY PRIOR EMPNO = /* current */ MGR.

How do I create a hierarchical query in MySQL?

MySQL (still) doesn't support hierarchical queries (as other modern DBMS do). You will need to write a stored procedure or use a different datamodel. Possible duplicate of What are the options for storing hierarchical data in a relational database?

How do I use between in MySQL?

The MySQL BETWEEN OperatorThe BETWEEN operator selects values within a given range. The values can be numbers, text, or dates. The BETWEEN operator is inclusive: begin and end values are included.


1 Answers

MySQL doesn't support recursive queries so you have to do it the hard way:

  1. Select the rows where ParentID = X where X is your root.
  2. Collect the Id values from (1).
  3. Repeat (1) for each Id from (2).
  4. Keep recursing by hand until you find all the leaf nodes.

If you know a maximum depth then you can join your table to itself (using LEFT OUTER JOINs) out to the maximum possible depth and then clean up the NULLs.

You could also change your tree representation to nested sets.

like image 64
mu is too short Avatar answered Oct 15 '22 15:10

mu is too short