I'm pretty new to SQL, trying to wrap my head around it, but it's getting a little confusing. Here's a simplified version of what I'm working with.
I have this table called people
:
+----+------------+-----------+
| 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 |
+----+------------+-----------+
The above table is a list of people. Their parent_id column refers to who their parents are. If they have no parents on the table, their parent_id is 0.
Now, I want to be able to get separate lists of each group of people: grandparents, children, and grandchildren.
It's easy to get grandparents (Larry and Kevin), I can just do this query:
SELECT name FROM people WHERE parent_id = 0
But when it comes to getting children (John, Larry, Jason, and Mildred) and grandchildren (Bob and Mabel), I'm lost.
In English, this would be the process of getting the children: "Get all the results from the table. For each one, look at their parent id. Find the result in the table that has that as their id. See that person's id, and if it's 0, the original person was a child. Add them to the list of what we will display."
For the grandchildren, it would be the same as above, but just with an additional step.
Does that make sense? How can I write my process above as a SQL query?