Home > Database > Mysql Tutorial > body text

Let's talk about aggregate functions in MySQL and practice paging queries!

青灯夜游
Release: 2022-01-10 19:49:13
forward
3511 people have browsed it

This article will take you through the aggregation functions in Mysql's built-in functions and how to perform paging queries. I hope it will be helpful to you.

Let's talk about aggregate functions in MySQL and practice paging queries!

MySQL aggregate functions and paging queries

Reference link:#MySQL database (mysql Installation/Basics/Advanced/Optimization)

https://www.bilibili.com/video/BV1iq4y1u7vj

We learned about SQL single-row functions before. In fact, there is another type of SQL function called aggregation (or aggregation, grouping) function, which is a function that summarizes a set of data. The input is a set of data and the output is a single value. [Related recommendations: mysql video tutorial]

1. Introduction to aggregate functions

What is an aggregate function

Aggregation functions act on a set of data and return a value for a set of data.

Lets talk about aggregate functions in MySQL and practice paging queries!

Aggregation function type

  • AVG()
  • SUM()
  • MAX()
  • MIN()
  • COUNT()

Aggregation function syntax

Lets talk about aggregate functions in MySQL and practice paging queries!

##Aggregation functions cannot be nested in calls

For example, calls in the form of "AVG(SUM(field name))" cannot occur.

1.1 AVG and SUM functions

You can use the AVG and SUM functions for

numeric data.

SELECT AVG(salary), MAX(salary),MIN(salary), SUM(salary)
FROM   employees
WHERE  job_id LIKE '%REP%';
Copy after login

1.2 MIN and MAX functions

You can use the MIN and MAX functions on data of

any data type.

SELECT MIN(hire_date), MAX(hire_date)
FROM employees;
Copy after login

1.3 COUNT function

  • COUNT(*)Returns the total number of records in the table, suitable for any data type.
  • SELECT COUNT(*)
    FROM   employees
    WHERE  department_id = 50;
    Copy after login
  • COUNT(expr) Returns the total number of records where expr is not empty.
  • SELECT COUNT(commission_pct)
    FROM   employees
    WHERE  department_id = 50; //忽略了Null值
    Copy after login

Calculate how many records there are in the table

    Method 1:
  • count(*)
  • Method 2:
  • count(1)
  • Method 3:
  • count (a specific field), but because the null value is ignored, it is not necessarily correct for

Question: Which one is better to use count(*), count(1), count(column name)?

Actually, for # There is no difference in the tables of ##MyISAM Engine

. There is a counter inside this engine to maintain the number of rows, but COUNT(*) is slightly more efficient.

Innodb engine tables use

count(*), count(1) directly reads the number of rows, the complexity is O(n), because innodb really has to count it once. But it is better than the specific count (column name).

Question: Can you use count(column name) instead of count(*)?

Do not use count(column name) instead
count(*)

, count(*) is the standard syntax for counting rows defined by SQL92, which has nothing to do with the database, and has nothing to do with NULL or non-NULL. Note:

count(*)

will count rows with a NULL value, while count(column name) will not count rows with a NULL value in this column.

Note:

    The above grouping functions
  • ignore null values

  • Can be used with distinct to implement deduplication operations
  • A separate introduction to the count function, generally use count(*) to count the number of rows
  • The fields queried together with the grouping function are required to be the fields after group by

2. GROUP BY

2.1 Basic usage

Lets talk about aggregate functions in MySQL and practice paging queries!

You can use the GROUP BY clause to divide the data in the table into Several groups, the syntax is as follows:

SELECT column, group_function(column)
FROM table
[WHERE	condition]
[GROUP BY  group_by_expression]
[ORDER BY  column];
Copy after login

Clearly: WHERE must be placed after FROM

1,
in the SELECT list All columns that are not included in the group function should be included in the GROUP BY clause

SELECT   department_id, AVG(salary)
FROM     employees
GROUP BY department_id ;
Copy after login

Lets talk about aggregate functions in MySQL and practice paging queries!2. Columns included in the GROUP BY clause do not have to be Included in a SELECT list

SELECT   AVG(salary)
FROM     employees
GROUP BY department_id ;
Copy after login

2.2 Grouping using multiple columns

SELECT   department_id AS dept_id, job_id, SUM(salary)
FROM     employees
GROUP BY department_id, job_id ;
Copy after login
Lets talk about aggregate functions in MySQL and practice paging queries!

Lets talk about aggregate functions in MySQL and practice paging queries!

2.3 Using WITH ROLLUP in GROUP BY

使用WITH ROLLUP关键字之后,在所有查询出的分组记录之后增加一条记录,该记录计算查询出的所有记录的总和,即统计记录数量。

SELECT department_id,AVG(salary)
FROM employees
WHERE department_id > 80
GROUP BY department_id WITH ROLLUP;
Copy after login

注意: 当使用ROLLUP时,不能同时使用ORDER BY子句进行结果排序,即ROLLUP和ORDER BY是互相排斥的,当然这是只在5.7才存在的

3. HAVING(过滤数据)

3.1 基本使用

Lets talk about aggregate functions in MySQL and practice paging queries!

过滤分组:HAVING子句

  • 行已经被分组。

  • 使用了聚合函数。

  • 满足HAVING 子句中条件的分组将被显示。

  • HAVING 不能单独使用,必须要跟 GROUP BY 一起使用。

Lets talk about aggregate functions in MySQL and practice paging queries!

SELECT   department_id, MAX(salary)
FROM     employees
GROUP BY department_id
HAVING   MAX(salary)>10000 ;
Copy after login

Lets talk about aggregate functions in MySQL and practice paging queries!

非法使用聚合函数 : 不能在 WHERE 子句中使用聚合函数来代替过滤条件。如下:

SELECT   department_id, AVG(salary)
FROM     employees
WHERE    AVG(salary) > 8000
GROUP BY department_id;
Copy after login

练习:查询部门id为10,20,30,40这4个部门中最高工资比10000高的部门信息

#方式1:推荐,执行效率高于方式2.
SELECT department_id,MAX(salary)
FROM employees
WHERE department_id IN (10,20,30,40)
GROUP BY department_id
HAVING MAX(salary) > 10000;

#方式2:
SELECT department_id,MAX(salary)
FROM employees
GROUP BY department_id
HAVING MAX(salary) > 10000 AND department_id IN (10,20,30,40);
Copy after login

结论:

  • 当过滤条件中有聚合函数时,则此过滤条件必须声明在HAVING中。

  • 当过滤条件中没有聚合函数时,则此过滤条件声明在WHERE中或HAVING中都可以。但是,建议大家声明在WHERE中

3.2 WHERE和HAVING的对比

1. 从适用范围上来讲,HAVING的适用范围更广。 
2. 如果过滤条件中没有聚合函数:这种情况下,WHERE的执行效率要高于HAVING
Copy after login

区别1:WHERE 可以直接使用表中的字段作为筛选条件,但不能使用分组中的计算函数作为筛选条件;HAVING 必须要与 GROUP BY 配合使用,可以把分组计算的函数和分组字段作为筛选条件。

这决定了,在需要对数据进行分组统计的时候,HAVING 可以完成 WHERE 不能完成的任务。这是因为,在查询语法结构中,WHERE 在 GROUP BY 之前,所以无法对分组结果进行筛选。HAVING 在 GROUP BY 之后,可以使用分组字段和分组中的计算函数,对分组的结果集进行筛选,这个功能是 WHERE 无法完成的。另外,WHERE排除的记录不再包括在分组中。

区别2:如果需要通过连接从关联表中获取需要的数据,WHERE 是先筛选后连接,而 HAVING 是先连接后筛选。 这一点,就决定了在关联查询中,WHERE 比 HAVING 更高效。因为 WHERE 可以先筛选,用一个筛选后的较小数据集和关联表进行连接,这样占用的资源比较少,执行效率也比较高。HAVING 则需要先把结果集准备好,也就是用未被筛选的数据集进行关联,然后对这个大的数据集进行筛选,这样占用的资源就比较多,执行效率也较低。

小结如下:


优点缺点
WHERE(分组前筛选)先筛选数据再关联,执行效率高不能使用分组中的计算函数进行筛选
HAVING(分组后筛选)可以使用分组中的计算函数在最后的结果集中进行筛选,执行效率较低

开发中的选择:

WHERE 和 HAVING 也不是互相排斥的,我们可以在一个查询里面同时使用 WHERE 和 HAVING。包含分组统计函数的条件用 HAVING,普通条件用 WHERE。这样,我们就既利用了 WHERE 条件的高效快速,又发挥了 HAVING 可以使用包含分组统计函数的查询条件的优点。当数据量特别大的时候,运行效率会有很大的差别。一般来讲,能用分组前筛选的,尽量使用分组前筛选,提高效率

4. 回顾:分页查询 ★

应用场景:当要显示的数据,一页显示不全,需要分页提交sql请求

语法:

  select 查询列表
  from 表
  【join type join 表2
  on 连接条件
  where 筛选条件
  group by 分组字段
  having 分组后的筛选
  order by 排序的字段】
  limit 【offset,】size;
  offset 要显示条目的起始索引(起始索引从0开始)
  size 要显示的条目个数
Copy after login

特点:

  • limit语句放在查询语句的最后

  • 公式

    select 查询列表
    from 表
    limit (page-1)*size,size;
    Copy after login

假设size=10,即每页显示10条记录,page从1开始,即第一页

  • page=1,则显示条目的起始索引为0,页面显示0-10条
  • page=2,则显示条目的起始索引为10,页面显示11-20条
  • page=3,则显示条目的起始索引为20,页面显示21-30条

案例1:查询前五条员工信息

SELECT * FROM employees LIMIT 0,5;
SELECT * FROM employees LIMIT 5;
Copy after login

案例2:查询第11条——第25条

SELECT * FROM employees LIMIT 10,15;
Copy after login

案例3: 有奖金的员工信息,并且工资较高的前10名显示出来

SELECT *
FROM employees 
WHERE commission_pct IS NOT NULL 
ORDER BY salary DESC
LIMIT 10 ;
Copy after login

5. SELECT的执行过程

5.1 SELECT语句的完整结构

#方式1:sql92语法:
SELECT ...,....,...
FROM ...,...,....
WHERE 多表的连接条件
AND 不包含组函数的过滤条件
GROUP BY ...,...
HAVING 包含组函数的过滤条件
ORDER BY ... ASC/DESC
LIMIT ...,...

#方式2:sql99语法
SELECT ...,....,...
FROM ... JOIN ... 
ON 多表的连接条件
JOIN ...
ON ...
WHERE 不包含组函数的过滤条件
AND/OR 不包含组函数的过滤条件
GROUP BY ...,...
HAVING 包含组函数的过滤条件
ORDER BY ... ASC/DESC
LIMIT ...,...

#其中:
#(1)from:从哪些表中筛选
#(2)on:关联多表查询时,去除笛卡尔积
#(3)where:从表中筛选的条件
#(4)group by:分组依据
#(5)having:在统计结果中再次筛选
#(6)order by:排序
#(7)limit:分页
Copy after login

5.2 SELECT执行顺序

你需要记住 SELECT 查询时的两个顺序:

1. 关键字的顺序是不能颠倒的:

SELECT ... FROM ... WHERE ... GROUP BY ... HAVING ... ORDER BY ... LIMIT...
Copy after login

2.SELECT 语句的执行顺序(在 MySQL 和 Oracle 中,SELECT 执行顺序基本相同):

FROM -> WHERE -> GROUP BY -> HAVING -> SELECT 的字段 -> DISTINCT -> ORDER BY -> LIMIT
Copy after login

Lets talk about aggregate functions in MySQL and practice paging queries!

比如你写了一个 SQL 语句,那么它的关键字顺序和执行顺序是下面这样的:

SELECT DISTINCT player_id, player_name, count(*) as num # 顺序 5
FROM player JOIN team ON player.team_id = team.team_id # 顺序 1
WHERE height > 1.80 # 顺序 2
GROUP BY player.team_id # 顺序 3
HAVING num > 2 # 顺序 4
ORDER BY num DESC # 顺序 6
LIMIT 2 # 顺序 7
Copy after login

在 SELECT 语句执行这些步骤的时候,每个步骤都会产生一个虚拟表,然后将这个虚拟表传入下一个步骤中作为输入。需要注意的是,这些步骤隐含在 SQL 的执行过程中,对于我们来说是不可见的。

从这里的执行顺序我们也看出来了,因为where是先筛选的,因此group by语句事先分组,参与分组的数据要少,因此执行效率要高

5.3 SQL 的执行原理

SELECT 是先执行 FROM 这一步的。在这个阶段,如果是多张表联查,还会经历下面的几个步骤:

  • 首先先通过 CROSS JOIN 求笛卡尔积,相当于得到虚拟表 vt(virtual table)1-1;

  • 通过 ON 进行筛选,在虚拟表 vt1-1 的基础上进行筛选,得到虚拟表 vt1-2;

  • 添加外部行。如果我们使用的是左连接、右链接或者全连接,就会涉及到外部行,也就是在虚拟表 vt1-2 的基础上增加外部行,得到虚拟表 vt1-3。

当然如果我们操作的是两张以上的表,还会重复上面的步骤,直到所有表都被处理完为止。这个过程得到是我们的原始数据。

当我们拿到了查询数据表的原始数据,也就是最终的虚拟表 vt1,就可以在此基础上再进行 WHERE 阶段。在这个阶段中,会根据 vt1 表的结果进行筛选过滤,得到虚拟表 vt2

然后进入第三步和第四步,也就是 GROUP 和 HAVING 阶段。在这个阶段中,实际上是在虚拟表 vt2 的基础上进行分组和分组过滤,得到中间的虚拟表 vt3vt4

当我们完成了条件筛选部分之后,就可以筛选表中提取的字段,也就是进入到 SELECT 和 DISTINCT 阶段

首先在 SELECT 阶段会提取想要的字段,然后在 DISTINCT 阶段过滤掉重复的行,分别得到中间的虚拟表 vt5-1vt5-2

当我们提取了想要的字段数据之后,就可以按照指定的字段进行排序,也就是 ORDER BY 阶段,得到虚拟表 vt6

最后在 vt6 的基础上,取出指定行的记录,也就是 LIMIT 阶段,得到最终的结果,对应的是虚拟表 vt7

当然我们在写 SELECT 语句的时候,不一定存在所有的关键字,相应的阶段就会省略。

同时因为 SQL 是一门类似英语的结构化查询语言,所以我们在写 SELECT 语句的时候,还要注意相应的关键字顺序,**所谓底层运行的原理,就是我们刚才讲到的执行顺序。**更细致的内容参考后续的高级篇架构

6. 课后练习

综合练习1

1.where子句可否使用组函数进行过滤? No

2.查询公司员工工资的最大值,最小值,平均值,总和

SELECT MAX(salary), MIN(salary), AVG(salary), SUM(salary)
FROM employees;
Copy after login

3.查询各job_id的员工工资的最大值,最小值,平均值,总和

SELECT job_id, MAX(salary), MIN(salary), AVG(salary), SUM(salary)
FROM employees
GROUP BY job_id;
Copy after login

4.选择具有各个job_id的员工人数

SELECT job_id, COUNT(*)
FROM employees
GROUP BY job_id;
Copy after login

5.查询员工最高工资和最低工资的差距(DIFFERENCE)

SELECT MAX(salary), MIN(salary), MAX(salary) - MIN(salary) DIFFERENCE
FROM employees;
Copy after login

6.查询各个管理者手下员工的最低工资,其中最低工资不能低于6000,没有管理者的员工不计算在内

SELECT manager_id, MIN(salary)
FROM employees
WHERE manager_id IS NOT NULL
GROUP BY manager_id
HAVING MIN(salary) > 6000;
Copy after login

7.查询所有部门的名字,location_id,员工数量和平均工资,并按平均工资降序

SELECT department_name, location_id, COUNT(employee_id), AVG(salary) avg_sal
FROM employees e RIGHT JOIN departments d
ON e.`department_id` = d.`department_id`
GROUP BY department_name, location_id
ORDER BY avg_sal DESC;
Copy after login

1Lets talk about aggregate functions in MySQL and practice paging queries!

8.查询每个工种、每个部门的部门名、工种名和最低工资

SELECT department_name,job_id,MIN(salary)
FROM departments d LEFT JOIN employees e
ON e.`department_id` = d.`department_id`
GROUP BY department_name,job_id
Copy after login

综合练习2

1.简单的分组

案例1:查询每个工种的员工平均工资

SELECT AVG(salary),job_id
FROM employees
GROUP BY job_id;
Copy after login

案例2:查询每个位置的部门个数

SELECT COUNT(*),location_id
FROM departments
GROUP BY location_id;
Copy after login

2.可以实现分组前的筛选

案例1:查询邮箱中包含a字符的 每个部门的最高工资

SELECT MAX(salary),department_id
FROM employees
WHERE email LIKE '%a%'
GROUP BY department_id;
Copy after login

案例2:查询有奖金的每个领导手下员工的平均工资

SELECT AVG(salary),manager_id
FROM employees
WHERE commission_pct IS NOT NULL
GROUP BY manager_id;
Copy after login

3.分组后筛选

案例1:查询哪个部门的员工个数>5

#①查询每个部门的员工个数
SELECT COUNT(*),department_id
FROM employees
GROUP BY department_id;

#② 筛选刚才①结果
SELECT COUNT(*),department_id
FROM employees
GROUP BY department_id
HAVING COUNT(*)>5;
Copy after login

案例2:每个工种有奖金的员工的最高工资>12000的工种编号和最高工资

SELECT job_id,MAX(salary)
FROM employees
WHERE commission_pct IS NOT NULL
GROUP BY job_id
HAVING MAX(salary)>12000;
Copy after login

案例3:领导编号>102的每个领导手下的最低工资大于5000的领导编号和最低工资

SELECT manager_id,MIN(salary)
FROM employees
GROUP BY manager_id
Where manager_id>102
HAVING MIN(salary)>5000;
Copy after login

4.添加排序

案例:每个工种有奖金的员工的最高工资>6000的工种编号和最高工资,按最高工资升序

SELECT job_id,MAX(salary) m
FROM employees
WHERE commission_pct IS NOT NULL
GROUP BY job_id
HAVING m>6000
ORDER BY m ;
Copy after login

5.按多个字段分组

案例:查询每个工种每个部门的最低工资,并按最低工资降序

SELECT MIN(salary),job_id,department_id
FROM employees
GROUP BY department_id,job_id
ORDER BY MIN(salary) DESC;
Copy after login

更多编程相关知识,请访问:编程入门!!

The above is the detailed content of Let's talk about aggregate functions in MySQL and practice paging queries!. For more information, please follow other related articles on the PHP Chinese website!

source:juejin.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template