2
How do I count how many "children" such a row have, and at the same time list all the records in the table?
I have the table categorias
, 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 have 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 the query is fundamentally wrong, because you’re telling me the part I don’t want. But how do I bring the amount of children that the current line has to the complete information?
I don’t know if it would work, I can’t test it, but it would be something like...
SELECT *, (SELECT Count(*) FROM categorias WHERE id_pai = cat.id_pai) FROM categorias as cat
?– Rafael Withoeft
@Rafaelwithoeft Almost that. It returned as in the query I have, only instead of Count working 1, it worked 2. I wanted ctg1 Count to work 2, and the other 0.
– Thomas
Try to change to
SELECT *, (SELECT Count(*) FROM categorias WHERE id_pai = cat.id) FROM categorias as cat
– Rafael Withoeft
@Rafaelwithoeft This query returned what I expected. I found the solution in the meantime, but you can post your answer which I accept as a solution.
– Thomas
Thomas I believe it is best you put as answer the solution you use... :)
– Rafael Withoeft