group by

group by 分组的功能,但要是排除哪些组,不能使用where,因为where过滤指定的是行而不是分组,看如下

使用where指定行

select cat_id,goods_name from goods where cat_id = 5;
+--------+------------+
| cat_id | goods_name |
+--------+------------+
|      5 | 诺基亚N96       |
+--------+------------+

如果使用where指定分组会出现分组错误

mysql> select cat_id,count(*) from goods where count(*)>5 group by cat_id;
ERROR 1111 (HY000): Invalid use of group function

使用having指定分组

mysql> select cat_id,count(*) from goods group by cat_id having count(*) > 5;
+--------+----------+
| cat_id | count(*) |
+--------+----------+
|      3 |       15 |
+--------+----------+

取出商品价格大于500,至少有三行商品的分组来

mysql> select cat_id,count(*) from goods where shop_price>500 group by cat_id ha
ving count(*)>3;
+--------+----------+
| cat_id | count(*) |
+--------+----------+
|      3 |       13 |
+--------+----------+
select 子句及其顺序
子句 说明 是否必须使用
select 要返回的列或者表达式
from 从中检索数据的表 仅在从表中选择数据时使用
where 行级过滤
group by 分组说明 仅在按组计算聚集时使用
having 组级过滤
order by 输出排序顺序
limit 要检索的行数
posted @ 2013-11-26 23:42  long896130895  阅读(224)  评论(0编辑  收藏  举报