我有两张桌子:
category
+----+------+ | ID | Name | +----+------+ | 1 | news | | 2 | blog | +----+------+
articles
+----+----------+---------------+ | ID | category | title | +----+----------+---------------+ | 1 | 1 | hello | | 2 | 2 | yamen | | 3 | 2 | stackoverflow | | 4 | 1 | nice day | +----+----------+---------------+
现在我需要显示每个类别名称及其中的文章总数。
答案 0 :(得分:0)
您只需要加入表格并使用适当的聚合函数对结果进行分组:
SELECT category.name, COUNT(articles.ID)
FROM category LEFT JOIN articles ON articles.category = category.ID
GROUP BY category.ID
答案 1 :(得分:0)
Select c.ID,
c.category,
count(a.title) as titlecount,
GROUP_CONCAT(a.title SEPARATOR ',') as titles
FROM category c
INNER JOIN article a on c.ID = a.category
group by c.ID