MySql获取列中每种元素的计数

时间:2009-02-03 09:23:39

标签: mysql

我有2个表格,结构如下..

category
{
  sub_cat_id - numeric
  sub_cat_name -  varchar
  main_cat_id - varchar (2 characters)
  main_cat_name -  varchar
}

products
{
  pid - autoincrement
  pname - varchar
  category (Will be either sub_cat_id or main_cat_id)
}

产品表

pid       pname       category
1         mobile      EL
2         shoes       1
3         shirt       1 
4         TV          EL
5         mp3 player  EL

我想得到products表中每个类别的计数,以便我的查询返回 2类别1和 3类别EL

有人可以帮我解决这个问题吗?

2 个答案:

答案 0 :(得分:6)

这应该是您追求的问题:

SELECT category, COUNT(*) FROM products GROUP BY category;

我建议您考虑类别表的设计,因为它可能会给您带来困难。

答案 1 :(得分:0)

注意空值:

mysql> select resourcetype,count(resourcetype) as num from resources group by resourcetype     order by num desc;
+-------------------+-------+
| resourcetype      | num   |
+-------------------+-------+
| COLLECTION        | 20036 |
| HIDDEN_RESOURCE   | 17443 |
| DEFAULT_CALENDAR  | 12528 |
| CALSCHED_INBOX    | 12528 |
| CALSCHED_OUTBOX   | 12528 |
| CAL_RESOURCE      | 12367 |
| SHARING_OUTBOX    |  2465 |
| SHARING_INBOX     |  2452 |
| CALENDAR          |     8 |
| HIDDEN_COLLECTION |     4 |
| NULL              |     0 |
+-------------------+-------+

mysql> select count(*) from resources where resourcetype is null;
+----------+
| count(*) |
+----------+
|       56 |
+----------+