sql按值堆栈按不同的值计算

时间:2015-07-14 08:39:04

标签: mysql sql join

我的数据库是这样的:

table1(article)
id | name | description | cat_id
0 | val1 |   desc1     |   1
1 | val2 |   desc2     |   2
2 | val3 |   desc3     |   1
3 | val4 |   desc4     |   2
4 | val5 |   desc5     |   1
5 | val6 |   desc6     |   2
6 | val7 |   desc7     |   0


table2(categories)
id | name 
0  | shoe
1  | glove
2  | hat

它应该返回:

articles_connected | categorie_name
        3          |  glove
        0          |  shoe
        3          |  hat

我试过了:

SELECT 
    COUNT(Category.id) as article_amount, Category.name
FROM 
    article_table as Article,
    category_table as Category
WHERE
    Category.id =  Article.cat_id

此代码只计为一个,不会拆分我的类别。我不确定会出现什么问题。

1 个答案:

答案 0 :(得分:2)

SELECT 
COUNT(Category.id) as article_amount, Category.name
FROM 
article_table as Article,
category_table as Category
WHERE
     Category.id =  Article.cat_id
group by Category.name