开发者

MYSQL Counting the number of records that are associated

开发者 https://www.devze.com 2023-02-24 09:18 出处:网络
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,

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;
0

精彩评论

暂无评论...
验证码 换一张
取 消