2

I have a table that lists a hierarchy of team members for an MLM. I am trying to figure out how to query the table most efficiently in MySQL so I can output the results in PHP.

I have learned in research that nested queries or nested queries in PHP while loops are not ideal, yet when I look at MySQL joins, I don't see how to access the information correctly.

Table Values (Table Name is MLM):

ID  Upline   FName

1     1      Joe    (he is at the top of the hierarchy)
2     1      Jane   (Jane is directly under Joe)
3     2      Jack
4     3      Jill

To find out the names of all these people reporting under Joe?

Select FName from MLM where Upline = 1;
and
Select FName from MLM where Upline in (Select FName from MLM where Upline = 1);
and
Select FName from MLM where Upline in (Select FName from MLM where Upline in (Select FName from MLM where Upline = 1));

This isn't good to start, and not knowing how many levels will be under Joe, it isn't scalable.

Can you please let me know how I can best query this information or combine a PHP mysql_fetch_array in a while loop to find and echo all the values?

2 Answers 2

1

Not commonly known, but you can join a table on itself. You will have to give each instance a seperate alias so that you can refer to them as required.

The following query will retrieve all the people with the same Upline as Joe:

SELECT m2.* FROM MLM m1
JOIN MLM m2 ON m1.Upline = m2.Upline
WHERE m1.FName LIKE "Joe"

If you only want the people reporting to Joe, and not Joe himself, you can do something like this:

SELECT m2.* FROM MLM m1
JOIN MLM m2 ON m1.Upline = m2.Upline
WHERE m1.FName LIKE "Joe"
AND m1.FName <> m2.FName
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you for showing me the direction to go in... I will study self-joins and see if I can get this to work.
No problem, good luck :) Let me know if you need any more help.
0

Representing hierarchical data in database is tricky. You can think about either of the following :-

  1. Re design your table such that it is easy to identify the hierarchy - Check this link for better understanding of the limitations and problems with subquery hierarchy Managing Hierarchical Data in MySQL OR
  2. Select * from the table and in your php code create the hierarchy by iterating through the results.

Other than this, if you go on for subqueries on subqueries, you are not going to be anywhere near a practical solution.

1 Comment

Thank you for the link. I just purchased Joe's book and will study hierarchical data models.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.