I need to know if there is a possible way doing this with out subquery..
Here is my table structure:
id-name-father_id
1 joe 0
2 mark 0
3 muller 0
4 miki 2
5 timi 2
6 moses 2
7 david 1
8 momo 0
9 daniel 0
10 ermi 3
My table logic is
-
0means he is not a child of some one -
1+mean that he is son of man in that row.
Note: if some one have a child, he still
will have 0 in father id (it’s mean there is not grand-fathers in my table)
My query is :
SELECT id, name, count(id=father_id) as sons
WHERE father_id = 0
What I want to get is a list of non-children (father_id=0) and sum
the childrens it has.
Is there a way to get the results without a subquery?
This should do it (MySQL):
According to Gary we need to add
nametoGROUP BYin other SQL databases:We are joing the table with itself here. So we join all parents with their children.
This will lead to a result like that:
But now we have each parent several times. So we are GROUP’ing the whole thing over the parent’s id, which will result in the following: