@tingyuge
2016-08-04T09:55:08.000000Z
字数 1155
阅读 1196
MySQL进阶
MySQL
分组允许把数据分为多个逻辑组,以便能对每组数据进行聚集计算。
SELECT
语句的GROUP BY
子句中建立的。
SELECT columnName1, COUNT(columnName2) AS coluMnName FROM tableName GROUP BY columnName1;
GROUP BY
子句指示MySQL分组数据,然后对每组而不是整个结果集进行聚集。GROUP BY
子句必须出现在WHERE
子句之后,ORDER BY
之前。GROUP BY
分组数据外,还能够使用HAVING
子句过滤分组,规定包括哪些分组,排除哪些分组。例如,想要列出至少有两个订单的所有顾客,为了得到这种数据,必须基于完整的分组而不是个别的行进行过滤。
SELECT columnName1, COUNT(columnName2) AS columnName FROM tableName GROUP BY columnName1 HAVING columnName > 2;
HAVING
与WHERE
的区别:WHERE
在数据分组前进行过滤,HAVING
在数据分组后进行过滤,WHERE
排除的行不在分组中,这可能会改变计算值,从而影响HAVING
子句基于这些值过滤的分组.
SELECT * FROM tableName WHERE columnName = value GROUP BY columnName HAVING columnName ORDER BY columnName LIMIT num1,num2;
# 查询订单表中订单物品为TNT2的所有订单
SELECT order_num FROM orderitems WHERE pro_id = 'TNT2';
# 假设上条语句结果为2005,2007
SELECT cust_id FROM orders WHERE order_num IN (2005,2007);
# 假设上条语句结果为1001,1004
SELECT cust_name FROM custmoers WHERE cust_id IN (1001, 1004);
# 上条语句查询出customer表中用户的用户名
第二种方法为使用子查询,将上述的三条语句组合在一起:
SELECT cust_name FROM custmoers WHERE cust_id IN (
SELECT cust_id FROM orders WHERE order_num IN (SELECT order_num
FROM orderitems WHERE pro_id = 'TNT2')
);