This is an extension of another question I just asked. I learned there how to properly write a SQL query to get the desired result that I need. But when I tried to apply it to my actual use, I found something else that I need.
This is a simplified version of the table that I have:
+-----+-------------+-----------+
| id | name | parent_id |
+-----+------------+-----------+
| 1 | Bob | 3 |
| 2 | John | 5 |
| 3 | Larry | 4 |
| 4 | Kevin | 0 |
| 5 | Kyle | 0 |
| 6 | Jason | 5 |
| 7 | Mildred | 4 |
| 8 | Mabel | 6 |
| 9 | Amber | 4 |
| 10 | Devon | 5 |
| 11 | Zack | 0 |
| 12 | Alfred | 11 |
| 13 | Robert | 11 |
| 14 | Keith | 11 |
+----+-------------+-----------+
(I added a few more since my last question, just so there's more examples) Now I wanted to be able to get lists of the parents, the children, and the grandchildren. Here's the queries I found to get those:
Grandparents
SELECT name FROM people WHERE parent_id = 0
Children
SELECT c.name
FROM people p
JOIN people c ON c.parent_id = p.id
WHERE p.parent_id = 0
And grandchildren
SELECT gc.name
FROM people p
JOIN people c ON c.parent_id = p.id
JOIN people gc ON gc.parent_id = c.id
WHERE p.parent_id = 0
I'm trying to figure out something for the children, so I'll leave the others for now. That query above for children gives the following result:
+---------+
| name |
+---------+
| John |
| Larry |
| Jason |
| Mildred |
| Amber |
| Devon |
| Alfred |
| Robert |
| Keith |
+---------+
Which is good, but I need it ordered first by alphabetical order of first by the parent, then second by the child. So I add an ORDER BY to my query:
SELECT c.name
FROM people p
JOIN people c ON c.parent_id = p.id
WHERE p.parent_id = 0
ORDER BY p.name, c.name
Which gives me:
+---------+
| name |
+---------+
| Amber |
| Larry |
| Mildred |
| Devon |
| Jason |
| John |
| Alfred |
| Keith |
| Robert |
+---------+
Good. But now the issue is, I would also like to include the parents in this list, right above where their children are. Additionally, I would like some way to show whether the result is a parent or a child. So I was thinking of another column, called Rank
, which would have values of either 1 or 2, to indicate parent or child. So this is the result I want back:
+--------+------+
| name | rank |
+--------+------+
| Kevin | 1 |
| Amber | 2 |
| Larry | 2 |
| Mildred| 2 |
| Kyle | 1 |
| Devon | 2 |
| Jason | 2 |
| John | 2 |
| Zack | 1 |
| Alfred | 2 |
| Keith | 2 |
| Robert | 2 |
+--------+------+
Does that make sense? What query can I use to get that result?