首页 > 代码库 > mysql之分组

mysql之分组

1、创建分组 group by

SELECT vend_id, COUNT(*) AS num_prods FROM products
GROUP BY vend_id;

技术分享

在where字句之后,在order by字句之前。

2、过滤分组

HAVING 过滤分组,where过滤行

SELECT cust_id,COUNT(*) AS orders1 FROM orders
GROUP BY cust_id
HAVING COUNT(*) >=2;

技术分享

它列出具有两个以上产品且其价格大于等于4的供应商: 

SELECT vend_id,COUNT(*) AS num_prods FROM products
WHERE prod_price >=4
GROUP BY vend_id
HAVING COUNT(*) >=2;

 技术分享   

 

技术分享  技术分享

SELECT子句顺序

技术分享

 

mysql之分组