type
status
date
slug
summary
tags
category
icon
password
URL
Sep 1, 2022 09:23 AM

select * from student order by 排序字段1 排序方式1,排序字段2 排序方式2;
desc降序
asc升序
select * from student order by math asc , english asc;
注意:
如果有多个排序条件,则当前边的条件值一样时,才会判断第二条件
聚合函数
- count:计算个数
- 一般选择非空的列:主键
- count(*)
- max:计算最大值
- min:计算最小值
- sum:计算和
- avg:计算平均值
注意:聚合函数的计算,排除null值。
解洁方案:
- 选择不包含非空的列进行计算
- IFNULL函数
select max(math) from student;
select min(math) from student;
select sum(english) from student;
select ave(math) from student;
分组查询
- 语法:group by 分组字段;
- 注意:
- 分组之后查询的字段,分字字段、聚合函数。
- where和having的区别
- where在分组之前进行限定,如果不满足条件,则不参与分组
- having在分组之后进行限定,如果不满组结果,则不会被查询出来
- where后不可以跟聚合函数,having可以进行聚合函数的判断
select sex, ave(math) from student group by sex;
select sex, ave(math),count(id) from student group by sex;
select sex, ave(math),count(id) from student where math > 70 group by sex;
select sex, ave(math),count(id) from student where math > 70 group by sex having count(id) > 2;
分页查询
- 语法:limit开始的索引,每页查询的条数;
- 公式:开始的索引 = (当前的页码 - 1) * 每页显示的条数
- limit是一个MySQL“方言”
select * from student limit 0,3; —第一页
select * from student limit 3,3; —第二页
select * from student limit 6,3; —第三页
每页显示三条记录
约束
- 概念:对表中的数据进行限定,保证数据的正确行、有效性和完整性。
- 分类:
- 主键约束:primary key
- 非空约束:not null
- 唯一约束:unique
- 外键约束:foreign key
非空约束
create table stu(
id int,
name varchar(20) not null — name is not null
);
alter table stu modify name varchar(20);
alter table stu modify name varchar(20) not null;
唯一约束
create table stu(
id int,
phone_number varchar(20) unique
);
alter table stu drop index phone_number;
alter table stu modify phone_number varchar(20) unique;
主键约束
- 含义:非空且唯一
- 一张表只能有一个字段
- 主键就是表中记录的唯一标识
- 在创建表时,添加主键约束
create table stu(
id int primary key,
name varchar(20)
);
- 删除主键
—错误 alter table stu modify id int;
alter table stu drop primary key;
- 创建完成后,添加主键
alter table stu modify id int primary key;
- 自动增长:
- 概年:如果某一列是数值类型的,使用auto_increment可以来完成值得自动增长
- 在创建表时添加主键约束,并且完成自动增长
- 删除自动增长
- alter table stu modify id int;
- 添加自动增长
- alter table stu modify id int auto_increment;
create table stu(
id int primary key auto_increment,
name varchar(20)
);
外键约束:foreign key,让表与表产生关系,从而保证数据的正确性和完整性
- 在创建表时,可以添加外键
- 语法:
create table stu(
...
外键列
constraint 外键名称 foreign key (外键列名称) references 主表名称(主表列名称)
);
- 删除外键
- alter table employee drop foreign key emp_dept_fk;
- 在创建表之后添加外键
- alter table employee add constraint emp_dept_fk foreign key (dep_id) references department(id);
- alter table 表名 add constraint 外键名称 foreign key (外键字段名称) references 主表名称(主表列名称);
- 级联操作
- 添加级联操作
- 语法:
- 分类
- 级联更新:on update cascade
- 级联删除:on delete cascade
alter table 表名 add constraint 外键名称 foreign key (外键字段名称) references 主表名称(主表列名称) on update cascade on delete cascade;