How do I count how many "children" that row has, and at the same time list all records in the table?
I have the categorias
table, with the following data:
_________________________________
| id (PK) | nome | id_pai (FK) |
---------------------------------
| 1 | ctg1 | NULL |
| 2 | ctg2 | 1 |
| 3 | ctg3 | 1 |
---------------------------------
If I do SELECT *, COUNT(id_pai) FROM categorias GROUP BY id
I get the following result:
___________________________________________________
| id (PK) | nome | id_pai (FK) | COUNT(id_pai) |
---------------------------------------------------
| 1 | ctg1 | NULL | 0 |
| 2 | ctg2 | 1 | 1 |
| 3 | ctg3 | 1 | 1 |
---------------------------------------------------
The result I hope is:
___________________________________________________
| id (PK) | nome | id_pai (FK) | COUNT(id_pai) |
---------------------------------------------------
| 1 | ctg1 | NULL | 2 |
| 2 | ctg2 | 1 | 0 |
| 3 | ctg3 | 1 | 0 |
---------------------------------------------------
I know that the query is fundamentally wrong, because it is counting the part that I do not want. But how do I bring the amount of children that the current line has next to the complete information?