April 11, 2012

Counting rows from second table

Question by Goldie

I have two tables in mysql database

groups

id|name
_______
1 |red
2 |blue
3 |green
4 |white

and users

id|name  |group
_______________
1 |joe   |1
2 |max   |1
3 |anna  |2
4 |lisa  |2

So… joe and max are in the “red” group, anna and lisa are in the “blue” group.

How can I make simple listing of groups which would contain the number of
persons in that group
For example

red - 2
blue - 2
green - 0
white - 0

Answer by Mosty Mostacho

Give this a try:

select g.name, count(u.id) from groups g
left join users u on g.id = u.group
group by g.id, g.name

Answer by Starx

This should work

SELECT g.*, COUNT(DISTINCT u.id) FROM `groups` g
INNER JOIN `users` u on g.id = u.group
GROUP BY u.id

Author: Nabin Nepal (Starx)

Hello, I am Nabin Nepal and you can call me Starx. This is my blog where write about my life and my involvements. I am a Software Developer, A Cyclist and a Realist. I hope you will find my blog interesting. Follow me on Google+

...

Please fill the form - I will response as fast as I can!