mysql笔记(10)
Posted HardyDragon_CC
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了mysql笔记(10)相关的知识,希望对你有一定的参考价值。
使用 GROUP BY 分组数据,从输出中可以看到,供应商1001有3个产品,供应商1002有2个产品,供应商1003有7个产品,而供应商1005有2个产品;注意不要和 order by 弄混了。
SELECT vend_id ,count(*) AS num_prods
FROM products p
GROUP BY vend_id ;
使用WITH ROLLUP关键字,可以得到每个分组以及每个分组汇总级别(针对每个分组)的值
SELECT vend_id ,count(*) AS num_prods
FROM products p
GROUP BY vend_id WITH ROLLUP ;
使用 having 过滤分组,不是 where 。HAVING支持所有WHERE操作符。
SELECT cust_id ,count(*) AS orders
FROM orders o
GROUP BY cust_id ;
使用 having 过滤出 数量大于等于 2的分组。
SELECT cust_id ,count(*) AS orders
FROM orders o
GROUP BY cust_id
HAVING count(*)>=2;
HAVING和WHERE的差别 这里有另一种理解方法,WHERE在数据分组前进行过滤,HAVING在数据分组后进行过滤
下面列出具有2个(含)以上、价格为10(含)以上的产品的供应商;
-
WHERE子句过滤所有prod_price至少为10的行。然后按vend_id分组数据,HAVING子句过滤计数为2或2以上的分组。
-
如果没有WHERE子句,将会多检索出两行(供应商1002,销售的所有产品价格都在10以下;供应商1001,销售3个产品,但只有一个产品的价格大于等于10):
SELECT vend_id ,count(*) AS num_prods
FROM products p
WHERE prod_price >= 10
GROUP BY vend_id
HAVING count(*) >= 2;
SELECT vend_id ,count(*) AS num_prods
FROM products p
GROUP BY vend_id
HAVING count(*) >= 2;
SELECT order_num ,sum(quantity*item_price) AS ordertotal
FROM orderitems o
GROUP BY order_num
HAVING sum(quantity*item_price) >= 50;
可以使用 order by 利用 AS 生成的列排序;
SELECT order_num ,sum(quantity*item_price) AS ordertotal
FROM orderitems o
GROUP BY order_num
HAVING sum(quantity*item_price) >= 50
ORDER BY ordertotal;
SELECT order_num ,sum(quantity*item_price) AS ordertotal
FROM orderitems o
GROUP BY order_num
HAVING sum(quantity*item_price) >= 50
ORDER BY ordertotal DESC;
总结: 使用 group by 分组数据,使用 having 过滤分组,可以配合 where 和 其他函数使用。
以上是关于mysql笔记(10)的主要内容,如果未能解决你的问题,请参考以下文章
连接MySQL出现错误:ERROR 1045 (28000): Access denied for user ‘root‘@‘localhost‘ (using password: YES)(代码片段