I have two tables with parent – child relationship:
PARENT table with id as index
id | name
----------------
1 | Bob
2 | Mike
3 | Joe
CHILDREN table with id as index
id | parent | name
-------------------------
1 | 1 | Ronald
2 | 2 | Sammy
3 | 3 | Jenny
4 | 1 | Tara
5 | 3 | Jack
On my website I want to display list of all parents with count of their children as follows:
id | name | Children Count
-------------------------------
1 | Bob | 2
2 | Mike | 1
3 | Joe | 2
What is the efficient way to do this? Note that here I represented an analogous simplified version of my data structure, in my actual situation I have about 10000 records in my PARENT table and each parent has about 10 - 200 children.
In case you suggest to add a count column to PARENT table, do you know of any way such that the count will be automatically updated by MYSQL when I make a change in the CHILDREN table?
1 Answer