In MySQL SQL Stored Procedures, I need to retrieve all referrals under me at all levels while using where under referrals gives one level only
Sample Data
Name | Referred By |
---|---|
Alice | |
Bob | Alice |
Carol | Alice |
Dave | Bob |
Eve | Bob |
Frank | Carol |
Grace | Eve |
Helen | |
David | Helen |
Lucas | David |
Olivia | Lucas |
Sophia | Lucas |
Benjamin | Bob |
Expected Result
I asked for ‘Alice’ all level referrals then i need like this
- Bob
- Carol
- Dave
- Eve
- Frank
- Grace
- Benjamin
where these shouldn’t display (David,Lucas,Olivia ,Sophia) is no way related to Alice
2
Answers
Using a recursive cte is really convenient and should be strongly recommended. However, the job can be accomplished without one by using a stored procedure, which requires temporary tables. Only do it when recursive CTE is out of reach. i.e mysql version 5.x and below.
Let’s test it using
alice
as the original leader:Try
helen
this time:To put it in a nutshell, it’s possible to perform a recursive job without using a recursive CTE. But the coding is tedious. Should only do it when CTE is not available, and only as a last resort.