Home > Common Problem > body text

What are the mysql aggregate functions?

百草
Release: 2023-06-15 10:11:32
Original
4422 people have browsed it

MySQL aggregation functions include: 1. AVG(), applicable to fields or variables of numerical type, excluding NULL; 2. SUM(), applicable to fields or variables of numerical type, excluding NULL; 3. , MAX(), applicable to fields or variables of numerical type, string type, date and time type, excluding NULL; 4. MIN(), applicable to fields or variables of numerical type, string type, date and time type, not Contains NULL; 5. COUNT(), counts the number of specified fields appearing in the query structure, excluding NULL, etc.

What are the mysql aggregate functions?

The operating system of this tutorial: Windows 10 system, mysql version 8.0, Dell G3 computer.

1. Introduction to aggregate functions

What is an aggregate function
Aggregation functions act on a set of data and return a value to a set of data.

What are the mysql aggregate functions?

5 Common Aggregation Function Types

1. AVG(): Only applicable to numeric type fields or variables. Does not contain NULL values ​​

2, SUM(): only applicable to numeric type fields or variables. Does not contain NULL values

3, MAX(): Applicable to fields (or variables) of numeric type, string type, date and time type that do not contain NULL values

4, MIN(): Applicable to fields (or variables) of numeric type, string type, and date and time type that do not contain NULL values

5, COUNT(): Count the number of occurrences of the specified field in the query structure (excluding NULL values) )

2. GROUP BY

2.1 Basic use

What are the mysql aggregate functions?

You can use the GROUP BY clause Divide the data in the table into several groups

SELECT column, group_function(column)
FROM table
[WHEREcondition]
[GROUP BYgroup_by_expression]
[ORDER BYcolumn];
Copy after login

Make it clear: WHERE must be placed after FROM
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

What are the mysql aggregate functions?

Columns included in the GROUP BY clause do not have to be included in the SELECT list

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

What are the mysql aggregate functions?

2.2 Using multiple columns Group

What are the mysql aggregate functions?##

#需求:查询各个department_id,job_id的平均工资
SELECT   department_id dept_id, job_id, SUM(salary)
FROM     employees
GROUP BY department_id, job_id ;
Copy after login

What are the mysql aggregate functions?

2.3 Using WITH ROLLUP in GROUP BY


After using the WITH ROLLUP keyword, A record is added after all the queried group records, and this record calculates the sum of all the queried records, that is, the number of statistical records.

SELECT department_id,AVG(salary)
FROM employees
WHERE department_id > 80
GROUP BY department_id WITH ROLLUP;
Copy after login
Note: When using ROLLUP, the ORDER BY clause cannot be used at the same time to sort the results, that is, ROLLUP and ORDER BY are mutually exclusive.

3. HAVING

3.1 Basic use

What are the mysql aggregate functions?

Filter grouping: HAVING clause

1. Rows have been grouped.

2. Use aggregate functions.

3. Groups that meet the conditions in the HAVING clause will be displayed.

4. HAVING cannot be used alone and must be used together with GROUP BY.

What are the mysql aggregate functions?

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

What are the mysql aggregate functions?

Illegal use of aggregate functions: Aggregate functions cannot be used in the WHERE clause as follows:

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

What are the mysql aggregate functions?

3.2 Comparison between WHERE and HAVING

Difference 1: WHERE can directly use fields in the table as filtering conditions, but cannot use calculation functions in grouping as filtering conditions; HAVING must be used with Used together with GROUP BY, the group calculation function and group field can be used as filter conditions.

This determines that when data needs to be grouped for statistics, HAVING can complete tasks that WHERE cannot. This is because, in the query syntax structure, WHERE precedes GROUP BY, so the grouped results cannot be filtered. HAVING After GROUP BY, you can use the grouping field and the calculation function in the grouping to filter the grouped result set. This function cannot be completed by WHERE. Additionally, records excluded by WHERE are no longer included in the group.

Difference 2: If you need to obtain the required data from the related table through a connection, WHERE filters first and then connects, while HAVING connects first and then filters. This determines that WHERE is more efficient than HAVING in related queries. Because WHERE can be filtered first and connected with a smaller filtered data set and the associated table, this consumes less resources and has higher execution efficiency. HAVING needs to prepare the result set first, that is, use the unfiltered data set for association, and then filter this large data set, which takes up more resources and has lower execution efficiency.

WHEREHAVING

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

4. SELECT的执行过程

4.1 查询的结构

#方式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

4.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 -> LIMIT1
Copy after login

What are the mysql aggregate functions?

比如你写了一个 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 的执行过程中,对于我们来说是不可见的。

4.3 SQL 的执行原理

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

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

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

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

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

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

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

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

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

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

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

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

同时因为 SQL 是一门类似英语的结构化查询语言,所以我们在写 SELECT 语句的时候,还要注意相应的关键字顺序,所谓底层运行的原理,就是我们刚才讲到的执行顺序。

5.课后练习

#2.查询公司员工工资的最大值,最小值,平均值,总和
SELECT MAX(salary),MIN(salary),AVG(salary),SUM(salary)
FROM employees;
#3.查询各job_id的员工工资的最大值,最小值,平均值,总和 
SELECT job_id,MAX(salary),MIN(salary),AVG(salary),SUM(salary)
FROM employees
GROUP BY job_id;
#4.选择具有各个job_id的员工人数 
SELECT job_id,COUNT(*)
FROM employees
GROUP BY job_id;
# 5.查询员工最高工资和最低工资的差距(DIFFERENCE) 
SELECT MAX(salary),MIN(salary),MAX(salary) - MIN(salary) AS DIFFERENCE
FROM employees;
# 6.查询各个管理者手下员工的最低工资,其中最低工资不能低于6000,没有管理者的员工不计算在内
SELECT manager_id,MIN(salary)
FROM employees
WHERE manager_id IS NOT NULL
GROUP BY manager_id
HAVING MIN(salary) >= 6000;
# 7.查询所有部门的名字,location_id,员工数量和平均工资,并按平均工资降序
SELECT d.department_name,d.location_id,COUNT(employee_id),AVG(salary) "avg_sal"
FROM departments d LEFT JOIN employees e
ON d.department_id = e.department_id
GROUP BY department_name,location_id
ORDER BY avg_sal DESC;
# 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
Advantages Disadvantages
First filter the data and then associate it, the execution efficiency is high You cannot use the calculation function in the group to filter
You can use the calculation function in the grouping to filter the final result set, but the execution efficiency is low

The above is the detailed content of What are the mysql aggregate functions?. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!