按类别选择和计算行

时间:2013-01-16 09:21:42

标签: database

我尝试制作一些代码,但我发现了一些问题......

这是我的表......

类别表

+---------------------------+-----------------------+
+ id_category               +  name                 +
+---------------------------+-----------------------+
+   1                       +  Adidas               +
+   2                       +  Logo                 +
+   3                       +  Levis                +
+---------------------------+-----------------------+

项目表:

+---------+-----------------+-----------------------+
+ id_item +  id_category    +  name                 +
+---------+-----------------+-----------------------+
+   1     +      1          +  T-Shirt003           +
+   2     +      2          +  LogoShoes            +
+   3     +      3          +  Panty003             +
+---------------------------+-----------------------+

我希望得到这样的结果:

No.   Category         Total Item
1.     Adidas              1
2.     Logo                1
3.     Levis               1

任何人都可以帮助我吗?

1 个答案:

答案 0 :(得分:3)

使用GROUP BY选项

SELECT
    COUNT(item_table.id_category) as total,
    category_table.name
FROM
    category_table
    INNER JOIN item_table ON item_table.id_category = category_table.id_category
GROUP BY
    id_category