MYSQL Counting the number of records that are associated
Suppose I have a cat table and a catherder table with a one catherder to many 开发者_StackOverflow社区cats relationship. How would I write a query that along with typical attributes like color of hat, height, etc, I could have a count of how many cats each herder has where each cat herder is one record?
SELECT catherder.*, count(cat.id) AS cats_count
FROM catherder join cat
on catherder.id = cat.catherder_id
This should do the trick (not tested)
SELECT color,height,COUNT(cat.id) AS cats FROM
cats RIGHT JOIN catherder ON cats.id = catherder.id GROUP BY catherder.id;
精彩评论