加入并显示两个表中的信息

时间:2014-03-07 19:56:42

标签: mysql sql join

我有两张桌子:

  1. category

    +----+------+
    | ID | Name |
    +----+------+
    |  1 | news |
    |  2 | blog |
    +----+------+
    
  2. articles

    +----+----------+---------------+
    | ID | category |     title     |
    +----+----------+---------------+
    |  1 |        1 | hello         |
    |  2 |        2 | yamen         |
    |  3 |        2 | stackoverflow |
    |  4 |        1 | nice day      |
    +----+----------+---------------+
    
  3. 现在我需要显示每个类别名称及其中的文章总数。

2 个答案:

答案 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