Clinton
Clinton

Reputation: 33

How to select all categories and count number of each category articles in MySQL

Category table:

id, name
---------
1   cat1
2   cat2
3   cat3 
4   cat4

Article table:

id, cid, title
--------------
1   1    title1
2   3    title2
3   1    title3
4   2    title4   

How to select all categories and count number of each category articles in MySQL? I need a mysql query that will select all category and total count of articles belonging to each category and order by category id.

Expected output table:

+-------+-------+    
|  name | count |    
+-------+-------+    
|  cat1 |     2 |    
|  cat2 |     1 |    
|  cat3 |     1 |  
|  cat4 |     0 |  
+-------+-------+

Upvotes: 3

Views: 4726

Answers (5)

Srini
Srini

Reputation: 76

I hope this will work. Please check.

select
    Category.name.
    ifnull(count(Article.cid),0) as count
FROM
    Category
LEFT JOIN
    Article 
on
    Article.cid=Category.id
group by
    Category.Id 

Upvotes: 0

Brijal Savaliya
Brijal Savaliya

Reputation: 1091

You can also use subquery like

SELECT c.name,(select count(*) from article where cid = c.id) as count  FROM cat c WHERE 1 GROUP BY c.id 

Upvotes: 2

mitkosoft
mitkosoft

Reputation: 5316

SELECT
    c.`name`,
    COUNT(a.cid) AS `count`
FROM
    categories c
    LEFT JOIN article a ON c.id = a.cid
GROUP BY
    c.`name`
ORDER BY
    c.`name`

Upvotes: 3

Priyanshu
Priyanshu

Reputation: 881

select c.name,count(b.title)count from category a, article b where c.id = a.cid group by c.name order by a.cid;

Upvotes: 1

Murad Hasan
Murad Hasan

Reputation: 9583

Try this:

SELECT c.`name`, count(a.cid) as count FROM category
LEFT JOIN article
ON c.id = a.cid
GROUP BY a.cid

Upvotes: 1

Related Questions