mysql - 聚合查询

插入查询结果

把插入的结果,插入到另一个表里

sql 复制代码
insert into 表名 select 列名 from 表明......;

要求后面查询出来的列数和类型要和前面插入的表的结构匹配

sql 复制代码
create table student (id int, name varchar(20));

create table student2 (id int, name varchar(20));

show tables;

insert into student values(1,'张三'),(2,'李四'),(3,'王五');

select*from student;

select*from student2;

insert into student2 select * from student;

也可以进行指定列插入和查询

sql 复制代码
insert into student2 (name) select name from student;

列的名字可以不匹配

聚合函数

聚合函数是为了进行聚合查询

查询的时候,指定表达式==>>进行"列和列之间的运算"

聚合查询,就是在进"行和行之间的运算"'

聚合函数可以说是SQL的库函数

填的表达式必须是数字,不是数字也没有意义

COUNT

统计exam表中有多少条数据

sql 复制代码
select count(*) from exam;

不要随便加一些空格

先查询在相加

sql 复制代码
select count(chinese) from exam;

指定某个列,查询count 时忽略空值.select * 包含空值

SUM

统计所有学生的数学总分

sql 复制代码
select sum(math) from exam;

select sum(chinese + math + english) from exam;

里边可以写表达式,但是不能写两个列

AVG

统计英语成绩的平均分

sql 复制代码
select avg(english) from exam;

select avg(chinese + math + english) from exam;

select avg(chinese + math + english) as '平均总分' from exam;

即使列是整数,进行求平均值,还是能得到小数点~~

查询结果,是临时表 列的类型 和 原始数据的 列类型 不一定完全一致

MAX MIN

查询英语最高分,数学最低分

sql 复制代码
select max(english),min(math) from exam;

Group by 分组查询

把表的若干行进行分组,需要指定"分组依据" . 指定某个列,这个列值相同的行就会分到同一个组里

根据分组后的结果进行聚合查询

sql 复制代码
select 表达式 from 表名 group by 列名;

创建一个员工表

sql 复制代码
create table emp(id int,name varchar(20),role varchar(20),salay decimal(10,2));

insert into emp values (1, '张三', '开发', 10000),(2, '李四', '开发', 11000),
(3, '王五', '开发', 12000),(4, '赵六', '测试', 10000),
(5, '田七', '测试', 11000),(6, '周八', 'CEO', 20000);

select * from emp;

统计每个角色的人数

sql 复制代码
select count(name) from emp group by role;

统计每个角色的平均工资,最少工资,最高工资

having子句

分组之前指定条件:where

分组之后指定的条件:having

怎么看是分组之前还是分组之后, 此处主要看条件, 是分组之前能确定的.还是分组之后才能确定的

统计每一个岗位的平均薪资(去掉张三) 和 统计每个岗位的平均薪资小于15000的

sql 复制代码
select role, avg(salay) from emp where name != '张三' group by role;


select role, avg(salay) from emp group by role having avg(salay)< 15000;

内置函数

SQL中的函数调用,一般是通过select 语句来进行的, 把函数放到select这里的列

查询结果,就是函数

日期函数

sql 复制代码
select curdate() as '当前日期';

select now();

create table student(id int, name varchar(20), last_time datetime);

insert into student values(1,'张三','2026-06-22 19:13:00');

insert into student values(2,'李四',now());

select * from student;

select name, date(last_time) from student;

select adddate('2026-06-22', INTERVAL 3 day);

select datediff('2026-06-22','2020-12-29');

参考链接:https://dev.mysql.com/doc/refman/8.0/en/date-and-time-functions.html

字符串处理函数

utf8一个字符对应三个字节

sql 复制代码
select name, length(name), CHAR_LENGTH(name) from student;

select concat(name, '同学') from student;

参考链接:https://dev.mysql.com/doc/refman/8.0/en/string-functions.html

数学函数

sql 复制代码
select ads(-10);

select floor(-3.14);

select conv(15, 10, 16);

sElect floor((rand() * 100) + 1);

参考链接:https://dev.mysql.com/doc/refman/8.0/en/numeric-functions.html

其他常用函数