如何选择MySQL中每个类别文章的所有类别和计数

时间:2016-04-27 11:47:31

标签: php mysql categories

分类表:

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

文章表:

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

如何选择MySQL中每个类别文章的所有类别和计数?我需要一个mysql查询,它将选择属于每个类别的文章的所有类别和总数,并按类别ID排序。

预期输出表:

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

5 个答案:

答案 0 :(得分:2)

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`

答案 1 :(得分:1)

试试这个:

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

答案 2 :(得分:1)

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;

答案 3 :(得分:0)

我希望这会奏效。请检查。

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

答案 4 :(得分:0)

您也可以使用

之类的子查询
arr[1,:].sort()