Say I have a table:
user_id parent_id lev1 lev2 lev3 lev4
1 0 0 0 0 0
2 1 1 0 0 0
3 1 1 0 0 0
4 2 2 1 0 0
5 4 4 2 1 0
6 4 4 2 1 0
7 5 5 4 2 1
Basically, this is to keep track of parent-children hierarchy and I want to get how many children does a parent have. Below is the output I want:
parent_id children
1 5
2 4
3 0
4 3
5 1
6 0
7 0
I'd like to COUNT the combined lev1, lev2, lev3 and lev4 fields to count how many IDs all in all in those fields.
I read about UNION ALL but I can't seem to figure out how it operates. I'm thinking of a UNION ALL with a self JOIN?