For the problem I have a single table which store a Member's ID and His Referee's ID. This is something like a Multi-Level-Marketing plan where you join a company for some tasks and then someone join from your reference and appear under your downline and so on and so forth. The scheme I am using is not necessarily a binary tree, there can be many users under a single user.
I want to retrieve the entire tree under a specific user, I am using below query to retrieve the records but this is not the solution I want.
SELECT t1.user AS lvl1, t2.user AS lvl2, t3.user AS lvl3,
t4.user AS lvl4, t5.user AS lvl5
FROM reference t1
LEFT JOIN reference t2 ON t2.referee = t1.user
LEFT JOIN reference t3 ON t3.referee = t2.user
LEFT JOIN reference t4 ON t4.referee = t3.user
LEFT JOIN reference t5 ON t5.referee = t4.user
WHERE t1.referee = 1
This query will get me the tree structure under user 1 but only 5 level deep.
Now I want to retrieve the entire tree upto last level but cant figure out a way for same. Tree depth can be anything depending on the users referrals so I cannot even guess the depth (That wont make sense anyway).
All I want right now is to perform the JOIN
and keep watching the selected column (in our case user
) from last JOIN
to check if all the values in it are NULL
. If the column from last JOIN
is NULL
then it means the tree is completed and query should return the result.
Can anyone suggest a workaround?
I can make changes in the table structure if necessary but that should not effect the behavior of other operations.
Best Answer
Although MySQL has no CTE functionality, there are two major ways to create CTE expressions:
TECHNIQUE #1 : Write Stored Procedures to Traverse Recursively
Rather than Reinventing the Wheel, please see my past posts on how to make stored procedures
Oct 24, 2011
: Find highest level of a hierarchical field: with vs without CTEsOct 26, 2012
: Hierarchical queries without CTEsTECHNIQUE #2 : Iterate Based on the Tree's Maximum Depth
First, here is some sample data
When loaded, this is the data
Here is how you compute the maximum depth
Here is the maximum depth for the sample data
Using this principle, iterate for the
SELECT
columns and theLEFT JOIN
clausesHere is the SQL generated
Here is the big question, does the SQL work ??? Take the SQL and run it dynamically:
Here is the result:
I scripted this to give you a starting point and some homework. Here is what I mean: You probably don't want to see NULL columns. You could do one of two things:
NULL
toIFNULL(lvl1,'')
, GROUP_CONCAT all columns.Give it a Try !!!
UPDATE 2016-06-14 16:36 EDT
Someone just commented
Let's try it out
OK, it says the depth is 5. Is there visible proof of this ?
Guess what the output says ?
Just as my code predicted. The depth is 5 and the Dynamic SQL just proved it.