JimboSlice
JimboSlice

Reputation: 692

MySQL join and count according to its column value

If I have a MySQL table looking something like this:

breeds

id      name
-------------------------------
1       Labrador
2       Jack Russel Terrier
3       Shetland Sheepdog

And a MySQL table looking like this:

dogs

id      owner       breed    sex
-----------------------------------
1       Sara        1        f
2       Kent        1        f
3       Billy       1        m
4       Joe         2        f
5       Billy       2        m

Is it possible to run a MySQL query to get output like this:

id      name                  females   males
------------------------------------------------
1       Labrador              2         1
2       Jack Russel Terrier   1         1
3       Shetland Sheepdog     0         0

I would like to have a JOIN or similar that count the number of females/males from the dogs table.

Upvotes: 2

Views: 44

Answers (2)

Carsten Massmann
Carsten Massmann

Reputation: 28196

Or alternatively:

SELECT id, name, 
   (SELECT COUNT(*) FROM dogs WHERE breed=b.id AND sex='f') females,
   (SELECT COUNT(*) FROM dogs WHERE breed=b.id AND sex='m') males
FROM breeds b

see here: http://www.sqlfiddle.com/#!9/03da0/1

Upvotes: 1

Raging Bull
Raging Bull

Reputation: 18737

You can do this:

SELECT b.id,b.name,
       IFNULL(SUM(CASE WHEN sex='f' THEN 1 ELSE 0 END),0) as females,
       IFNULL(SUM(CASE WHEN sex='m' THEN 1 ELSE 0 END),0) as males
FROM breeds b LEFT JOIN
     dogs d on b.id=d.breed
GROUP BY b.id,b.name

Explanation:

using LEFT JOIN will include the record eventhough there is male/female count. IFNULL will replace the null value with 0.

Result:

id  name                females males
-------------------------------------
1   Labrador            2       1
2   Jack Russel Terrier 1       1
3   Shetland Sheepdog   0       0

Sample result in SQL Fiddle.

Upvotes: 2

Related Questions