文章目录
数据库分类
DDL
DML
DQL
DCL
DDL
数据库操作
查询
- 查询所有数据库:
SHOW DATABASES;
- 查询当前数据库:
SELECT DATABASE();
创建
CREATE DATABASE [IF NOT EXISTS] 数据库名 [DEFAULT CHARSET 字符集] [COLLATE 排序规则];
创建一个名为itcase的数据库
create database itcase;
假如itcase不存在, 就创建; 如果存在, 就不创建
create database if not exists itcase;
创建一个itinfo数据库, 并给它设置一个字符集
create database itinfo default charset utf8mb4;
删除
DROP DATABASE[ IF EXISTS ] 数据库名;
drop database itinfo;
如果存在test数据库就删除他, 如果不存在就不删除
drop database if exists test;
使用
USE 数据库名;
使用itcase数据库
use itcase;
表操作
创建
create table tb_user(
id int comment '编号',
name varchar(50) comment '姓名',
age int comment '年龄',
gender varchar(1) comment '性别'
) comment '用户表';
查询
-
查询当前数据库所有表:
SHOW TABLES;
-
查询表结构:
DESC 表名;
desc tb_user;
-
查询指定表的建表语句:
SHOW CREATE TABLE 表名
;show create table tb_user;
案例
设计一张员工信息表,要求如下
1.编号(纯数字)
2.员工工号(字符串类型,长度不超过10位)
3.员工姓名(字符串类型,长度不超过10位)
4.性别(男/女,存储一个汉字)
5.年龄(正常人年龄,不可能存储负数)6.身份证号(二代身份证号均为18位,身份证中有X这样的字符)
7.入职时间(取值年月日即可).
create table emp(
id int comment '编号',
workno varchar(10) comment '工号',
name varchar(10) comment '姓名',
gender char(1) comment '性别',
age tinyint unsigned comment '年龄',
idcard char(18) comment '身份证号',
entrydate date comment '入职时间',
) comment '员工表';
修改
-
添加字段:
alter table 表名 add 字段名 类型(长度) [comment注释] [约束];
为emp表增加一个新的字段 "昵称" 为nickname, 类型为varchar(20) alter table emp add nickname varchar(20) comment '昵称';
-
修改数据类型:
alter table 表名 modify 字段名 新数据类型 (长度);
-
修改字段名和字段类型:
alter table 表名 change 旧字段名 新字段名 类型(长度) [comment 注释] [约束];
将emp的nickname字段修改为username, 类型为varchar(30) alter table emp change nickname username varchar(30) commit '用户名';
-
修改表名:
alter table 表名 rename to 新表名;
将emp表的表名修改为employee alter table emp rename to employee;
删除
-
删除字段:
alter table 表名 drop 字段名;
将emp表的字段username删除 alter table emp drop username;
-
删除表:
drop table [ if exists ] 表名;
如果存在tb_user这张表, 就删除 ; 不存在就不删除 drop table if exists tb_user;
-
删除指定表, 并重新创建该表:
truncate table 表名;
删除employee表, 并重新创建 truncate table employee;
DML
添加数据
-
给指定字段添加数据:
insert into 表名(字段名1 , 字段名2 , ...) values (值1 , 值2 , ...);
insert into employee(id,workno,name,gender,age,idcard,entrydate) values (1,'1','Itcase','男',10,'123456789012345678','2000-01-01');
-
给全部字段添加数据:
insert into 表名 values(值1 , 值2 , ...);
insert into employee values (2,'2','张无忌','男',18,'123456789012345670','2005-01-01');
-
批量添加数据
-
给指定字段批量添加:
insert into 表名 (字段名1 , 字段名2 , ...) values (值1 , 值2 , ...) , (值1 , 值2 , ...) , (值1 , 值2 , ...);
-
给全部字段批量添加:
insert into 表名 values (值1 , 值2 , ...) , (值1 , 值2 , ...) , (值1 , 值2 , ...);
insert into employee values(3,'3','韦一笑','男',38,'123456789712345670','2005-01-01'),(4,'4','赵敏','女',18,12345675712345670,'1005-01-01');
-
修改数据
-
update 表名 set 字段名1=值1 , 字段名2=值2 , ...[where 条件];
修改语句的条件可以有, 也可以没有, 如果没有条件, 则会修改整张表的所有数据.
修改id为1的数据,将name修改为itheima
update employee set name = 'itheima' where id = 1;
修改id为1的数据,将name修改为 小昭,gender修改为女
update employee set name = '小昭' , gender = '女' where id = 1;
将所有的员工入职日期修改为 2008-01-01
update employee set entrydate = '2008-01-01';
删除数据
delete from 表名 [where 条件]
- delete语句的条件可以有, 也可以没有, 如果条件没有, 则会删除整张表的所有数据.
- delete语句不能删除某一个字段的值(可以使用update).
删除 gender 为女的员工
delete from employee where gender = '女';
删除所有员工
delete from employee;
DQL
基本查询
-
查询多个字段
- select 字段1 , 字段2 , 字段3 … from 表名;
- select * from 表名
-
设置别名: select 字段1 [as 别名1] , 字段2 [as 别名2] … from 表名;
-
去除重复记录: select distinct 字段列表 from 表名;
1. 查询指定字段 name ,workno ,age返回 select name,workno,age from emp; 2. 查询所有字段返回 select id, workno, name, gender, age, idcard, workaddress, entrydate from emp; select * from emp; 3. 查询所有员工的工作地址, 起别名 select workaddress as '工作地址' from emp; select workaddress '工作地址' from emp; 4.查询公司员工的上班地址(不要重复) select distinct workaddress '工作地址' from emp;
条件查询
-
select 字段列表 from 表名 where 条件列表;
1. 查询年龄等于 88 的员工 select * from emp where age = 88; 2. 查询年龄小于 20 的员工 select * from emp where age < 20; 3. 查询年龄小于等于 20 的员工 select * from emp where age <= 20; 4. 查询没有身份证号的员工 select * from emp where idcard is null; 5. 查询有身份证号的员工信息 select * from emp where idcard is not null; 6. 查询年龄不等于 88 的员工 select * from emp where age !=88; select * from emp where age <> 88; 7. 查询年龄在 15 岁(包含) 到 20岁(包含)之间的员工 select * from emp where age >= 15 && age <=20; select * from emp where age >= 15 and age <=20; select * from emp where age between 15 and 20; 8. 查询性别为 女 且年龄小于 25 岁的员工 select * from emp where gender = ‘女’ and age < 25; 9. 查询年龄等于 18 或 20 或 40的员工 select * from emp where age = 18 or age = 20 or age = 40; select * from emp where age in (18,20,40); 10. 查询姓名为两个字的员工 select * from emp where name like ‘__’; 注意是两个连续的下划线 11. 查询身份证号最后一位是x的员工 select * from emp where idcard like ’%x’ %表示前面不管是什么都可以, 最后一个是x. select * from emp where idcard like ‘_________________x’ 前面是17个下划线(因为身份证有18位)
聚合函数
-
select 聚合函数(字段列表) from 表名;
1. 统计该企业员工数量 select count(*) from emp; select count(idcard) from emp; 2. 统计该企业员工的平均年龄 select avg(age) from emp; 3. 统计该企业员工的最大年龄 select max(age) from emp; 4. 统计该企业员工的最小年龄 select min(*) from emp; 5. 统计西安地区员工年龄之和 select sum(age) from emp where workaddress = ‘西安’;
分组查询
-
select 字段列表 from 表名 [where 条件] group by 分组字段名 [having 分组后过滤条件]
-
where和having的区别
-
执行时机不同: where是分组之前进行过滤, 不满足where条件, 不参与分组; 而 having是分组之后对结果进行过滤.
-
判断条件不同: where不能对聚合函数进行判断, 而having可以.
注意: 执行顺序: where > 聚合函数 > having 分组之后, 查询的字段一般为聚合函数和分组字段, 查询其他字段无任何意义
-
1. 根据性别分组, 统计男性员工 和 女性员工的数量
select gender , count(*) from emp group by gender;
2. 根据性别分组, 统计男性员工 和 女性员工的平均年龄
select gender , avg(age) from emp group by gender;
3. 查询年龄小于 45 的员工, 并根据工作地址分组, 获取员工数量大于等于3的工作地址.
(1) select workaddress , count(*) from emp where age < 45 group by workaddress having count(*) >= 3;
(2) select workaddress , count(*) address_count from emp where age < 45 group by workaddress having address_count >= 3;
这里和第一种方法一样, 只不过给count(*)起了一个别名address_count
排序查询
-
select 字段列表 from 表名 order by 字段1 排序方式1 , 字段2 排序方式2 ;
-
排序方式
- ASC: 升序(默认值)
- DESC: 降序
1. 根据年龄对公司的员工进行升序排序.
select * from emp order by age asc ;
select * from emp order by age ; (默认值是升序)
2. 根据入职时间, 对员工进行降序排序.
select * from emp order by entrydate desc ;
3. 根据年龄对公司员工进行升序排序, 年龄相同 , 再按照入职时间进行降序排序.
select * from emp order by age asc , entrydate desc ;
分页查询
- select 字段列表 from 表名 limit 起始索引 , 查询记录数 ;
- 注意:
- (1) 起始索引从0开始, 起始索引 = (查询页码 - 1) * 每页显示记录数.
- (2) 分页查询是数据库的方言, 不同的数据库有不同的实现, MySQL中是limit.
- (3) 如果查询的是第一页数据 , 起始索引可以省略 , 直接简写为limit10.
1. 查询第1页员工数据, 每页展示10条记录
select * from emp limit 0,10;
select * from emp limit 10; 起始从0开始, 0可以省略.
2. 查询第2页员工数据, 每页展示10条记录. (页码-1)*页展示记录数
select * from emp limit 10,10; (2-1)*10
练习
按照需求完成如下DQL语句编写:
1. 查询年龄为20,21,22,23岁的员工信息:
select * from emp where gender = ‘女’ and age in ( 20,21,22,23 );
2. 查询性别为男,并且年龄在 20-40 岁(含)以内的姓名为三个字的员工。
select * from emp where gender = ‘男’ and age between 20 and 40 and name like ‘___’;
3. 统计员工表中年龄小于60岁的,男性员工和女性员工的人数:
select gender , count(*) from emp where age < 60 group by gender;
4. 查询所有年龄小于等于35岁员工的姓名和年龄,并对查询结果按年龄升序排序,如果年龄相同按入职时间降序排序。
select name , age from emp where age <= 35 order by age asc , entrydate desc ;
5. 查询性别为男,且年龄在20-40 岁(含)以内的前5个员工信息,对查询的结果按年龄升序排序,年龄相同按入职时间升序排序。
select * from emp where gender = ‘男’ and age between 20 and 40 order by age asc , enteydate asc limit 5 ;
DCL
管理用户
查询用户
use mysql;
select * from user;
创建用户
create user '用户名'@'主机名' identified by '密码';
修改用户密码
alter user '用户名'@'主机名' identified with mysql_native_password by '新密码';
删除用户
drop user '用户名'@'主机名';
1. 创建用户 itcase, 只能够在当前主机localhost访问 , 密码123456
create user ‘itcase’@’localhost’ identified by 123456 ;
2. 创建用户 heima , 可以在任意主机访问该数据库, 密码123456
create user ‘heima’@’%’ identified by 123456 ;
3. 修改用户 heima 的访问密码为1234;
alter user ‘heima’@’%’ identified with mysql_native_password by ‘1234’;
4. 删除itcase@localhost用户;
drop user ‘itcase’@’localhost’ ;
权限控制
查询权限
show grants for '用户名'@'主机名' ;
授予权限
grant 权限列表 on 数据库名.表名 to '用户名'@'主机名' ;
撤销权限
revoke 权限列表 on 数据库名.表名 from '用户名'@'主机名'
函数
字符串函数
-- concat
select concat('Hello','MySQL');
# 输出:Hello MySQL
-- lower
select lower('Hello');
# 输出:hello
-- upper
select upper('Hello');
# 输出:HELLO
-- lpad
select lpad('01',5,'-');
# 输出:---01
-- rpad
select rpad('01',5,'-');
# 输出:01---
-- trim
select trim(' Hello MySQL ');
# 输出:Hello MySQL(前面和后面的空格不在了, 中间的空格还在)
-- substring
select substring('Hello MySQL',1,5);
# 输出:Hello
# 由于业务需求变更,企业员工的工号,统一为5位数,目前不足5位数的全部在前面补0.比如: 1号员工的工号应该为00001
update emp set workno = lpad(workno,5,'0');
数值函数
-- ceil
select ceil(1.5);
# 2
-- floor
select floor(1.9);
# 1
-- mod
select mod(3,4);
# 3
-- rand
select rand();
# 随机数0~1
-- round
select round(2.345,2);
# 2.35
# 通过数据库的函数,生成一个六位数的随机数验证码
select lpad( round( rand()*1000000 , 0 ) , 6 , '0' );
日期函数
-- curdate()
select curdate();
# 2023-05-03
-- curtime()
select curtime();
# 10:09:46
-- now()
select now();
# 2023-05-03 10:09:46
-- year month day
select YEAR(now());
# 2023
select MONTH(now());
# 05
select DAY(now());
# 03
-- date_add
select date_add(now(),INTERVAL 3 DAY);
# 2023-05-06 10:14:34
select date_add(now(),INTERVAL 3 MONTH);
# 2023-08-03 10:14:34
-- datediff
select datediff('2021-12-01','2021-11-01');
# 30
select datediff('2021-11-01','2021-12-01');
# -30
# 查询所有员工的入职天数,并根据入职天数倒序排序
select name,datediff(curdate(),entrydate) as 'entrydays' from emp order by entrydays;
流程函数
-- if
select if(true,'Ok','Error');
# Ok
select if(false,'Ok','Error');
# Error
-- ifnull
select ifnull('Ok','Defaule');
# Ok
select ifnull(null,'Defaule');
# Default
-- case when then else end
# 需求: 查询emp表的员工姓名和工作地址(北京/上海 ---> 一线城市 , 其他 ---> 二线城市)
select
name,
(case workaddress when '北京' then '一线城市' when '上海' then '一线城市' else '二线城市' end) as '工作地址'
from emp;
-- 统计班级各个学员的成绩,展示的规则如下:
-- >= 85,展示优秀
-- >= 60,展示及格
-- 否则,展示不及格
select
id,
name,
(case when math >= 85 then '优秀' when math >=60 then '及格' else '不及格' end) '数学',
(case when english >= 85 then '优秀' when english >=60 then '及格' else '不及格' end) '英语',
(case when chinese >= 85 then '优秀' when chinese >=60 then '及格' else '不及格' end) '语文'
from score;
约束
概述
-
概念: 约束是作用于表中字段上的规则, 用于限制存储在表中的数据.
-
目的: 保证数据库中数据的正确, 有效性和完整性.
-
分类:
约束 描述 关键字 非空约束 限制该字段的数据不能为null NOT NULL 唯一约束 保证该字段的所有数据都是唯一、不重复的 UNIQUE 主键约束 主键是一行数据的唯一标识,要求非空且唯一 PRIMARY KEY 默认约束 保存数据时,如果未指定该字段的值,则采用默认值 DEFAULT 检测约束(8.0.16版本之后) 保证字段值满足某一个条件 CHECK 外键约束 用来让两张表的数据之间建立连接,保证数据的一致性和完整性 FOREIGN KEY
约束演示
根据需求, 完成表结构的创建
字段名 | 字段含义 | 字段类型 | 约束条件 | 约束关键字 |
---|---|---|---|---|
id | ID唯一标识 | int | 主键, 并且自动增长 | PRIMARY KEY,AUTO_INCREMENT |
name | 姓名 | varchar(10) | 不为空,并且唯一 | NOT NULL,UNIQUE |
age | 年龄 | int | 大于0,并且小于等于120 | CHECK |
status | 状态 | char(1) | 如果没有指定该值,默认为1 | DEFAULT |
gender | 性别 | char(1) | 无 |
-- 创建表
create table user(
id int primary key auto_increment comment '主键',
name varchar(10) not null unique comment '姓名',
age int check (age > 0 && age <= 120) comment '年龄',
status char(1) default '1' comment '状态',
gender char(1) comment '性别'
) comment '用户表';
-- 插入数据
insert into user(name,age,status,gender) values ('Tom1',19,'1','男'),('Tom2',25,'0','男');
-- 下面这条将会报错, 因为约束name不能为空;
insert into user(name,age,status,gender) values (null,19,'1','男');
外键约束
添加外键
删除外键
详细看如下示例:
-- 准备数据
-- 创建部门表
create table dept(
id int auto_increment comment 'ID' primary key,
name varchar(50) not null comment '部门名称',
)comment '部门表';
INSERT INTO dept (id,name) VALUES (1,'研发部'),(2,'市场部'),(3,'财务部'),(4,'销售部'),(5,'总经办');
-- 创建员工表
create table emp(
id int auto_increment comment 'ID' primary key,
name varchar(50) not null comment '姓名',
age int comment '年龄',
job varchar(20) comment '职位',
salary int comment '薪资',
entrydate date comment '入职时间',
managerid int comment '直属领导ID',
dept_id int comment '部门ID'
)comment '员工表';
INSERT INTO emp (id,name,age,job,salary,entrydate,managerid,dept_id) VALUES
(1,'金庸',66,'总裁',20000,'2000-01-01',null,5),
(2,'张无忌',20,'项目经理',12500,'2005-12-05',1,1),
(3,'杨逍',33,'开发',8400,'2000-11-03',2,1),
(4,'韦一笑',48,'开发',11000,'2002-02-05',2,1),
(5,'常遇春',43,'开发',10500,'2004-09-07',3,1),
(6,'小昭',19,'程序员鼓励师',6600,'2004-10-12',2,1);
-- 添加外键
alter table emp add constraint fk_emp_dept_id foreign key (dept_id) references dept(id);
-- 删除外键
alter table emp drop foreign key fk_emp_dept_id;
删除更新行为
行为 | 说明 |
---|---|
NO ACTION | 当在父表中删除/更新对应记录时,首先检查该记录是否有对应外键,如果有则不允许删除/更新。(与 RESTRICT 一致) |
RESTRICT | 当在父表中删除/更新对应记录时,首先检查该记录是否有对应外键,如果有则不允许删除/更新。(与 NO ACTION一致) |
CASCADE | 当在父表中删除/更新对应记录时,首先检查该记录是否有对应外键,如果有,则也删除/更新外键在子表中的记录。 |
SET NULL | 当在父表中删除对应记录时,首先检查该记录是否有对应外键,如果有则设置子表中该外键值为null(这就要求该外键允许取nul) |
SET DEFAULT | 父表有变更时,子表将外键列设置成一个默认的值(Innodb不支持) |
-- 外键的删除和更新行为
alter table emp add constraint fk_emp_dept_id foreign key (dept_id) references dept(id) on update cascade on delete cascade;
多表查询
多表关系
- 一对多(多对一)
- 多对多
-- 多对多演示
create table student(
id int auto_increment primary key comment '主键ID',
name varchar(10) comment '姓名',
no varchar(10) comment '学号'
) comment '学生表';
insert into student values (null,'黛绮丝','2000100101'),(null,'谢逊','2000100102'),(null,'殷天正','2000200103'),(null,'韦一笑','2000100104')
create table course(
id int auto_increment primary key comment '主键ID',
name varchar(10) comment '课程名称'
) comment '课程表';
insert into course values (null,'Java'),(null,'PHP'),(null,'MySQL'),(null,'Hadoop');
create table student_course(
id int auto_increment comment '主键' primary key,
studentid int not null comment '学生ID',
courseid int not null comment '课程ID',
constraint fk_courseid foreign key (courseid) references course (id),
constraint fk_studentid foreign key (studentid) references student (id)
)comment '学生课程中间表';
insert into student_course values (null,1,1),(null,1,2),(null,1,3),(null,2,2),(null,2,3),(null,3,4);
- 一对一
create table tb_user(
id int auto_increment primary key comment '主键ID',
name varchar(10) comment '姓名',
age int comment '年龄',
gender char(1) comment '1: 男,2: 女',
phone char(11) comment '手机号'
) comment '用户基本信息表';
create table tb_user_edu(
id int auto_increment primary key comment '主键ID',
degree varchar(20) comment '学历',
major varchar(50) comment '专业',
primaryschool varchar(50) comment '小学',
middleschool varchar(50) comment '中学',
university varchar(50) comment '大学',
userid int unique comment '用户ID',
constraint fk_userid foreign key (userid) references tb_user(id)
) comment '用户教育信息表';
insert into tb_user(id, name, age, gender,phone] values
(null,'黄渤',45,'1','18800001111'),
(null,'冰冰',35,'2','18800002222'),
(null,'码云',55,'1','18800008888'),
(null,'李彦宏',50,'1','18800009999');
insert into tb_user_edu(id, degree, major, primaryschool, middleschool,university,userid) values
(null,'本科','舞蹈','静安区第一小学','静安区第一中学','北京舞蹈学院',1),
(null,'硕士','表演','朝阳区第一小学','朝阳区第一中学','北京电影学院',2),
(null,'本科','英语','杭州市第一小学','杭州市第一中学','杭州师范大学',3),
(null,'本科','应用数学','阳泉第一小学','阳泉区第一中学','清华大学',4);
多表查询概述
- 指从多张表中查询数据.
-- 多表查询
select * from emp,dept;
- 笛卡尔积:笛卡尔乘积是指在数学中, 两个集合 A集合和B集合的所有的组合情况. (在多表查询时, 需要消除无效的笛卡尔积)
-- 消除笛卡尔积
select * from emp,dept where emp.dept_id = dept.id;
-
多表查询分类
-
连接查询
-
内连接:相当于查询A、B交集部分数据.
-
外连接:
-
左外连接:查询左表所有数据,以及两张表交集部分数据.
-
右外连接:查询右表所有数据,以及两张表交集部分数据
-
-
自连接:当前表与自身的连接查询,自连接必须使用表别名
-
-
子查询
-
内连接
-
隐式内连接
select 字段列表 from 表1,表2 where 条件 ...;
-
显式内连接
select 字段列表 from 表1 [ INNER ] JOIN 表2 ON 连接条件 ...;
-- 内连接演示
-- 1. 查询每一个员工的姓名 , 及关联的部门的名称(隐式内连接实现)
-- 表结构: emp, dept
-- 连接条件: emp.dept_id = dept.id
select emp.name , dept.name from emp , dept where emp.dept_id = dept.id ;
select e.name,d.name from emp e , dept d where e.dept_id = d.id;
-- 2. 查询每一个员工的姓名 , 及关联的部门的名称(显式内连接实现)
-- 表结构: emp, dept
-- 连接条件: emp.dept_id = dept.id
select e.name,d.name from emp e inner join dept d on e.dept_id = d.id;
-- inner关键字也是可以省略掉的
select e.name,d.name from emp e join dept d on e.dept_id = d.id;
外连接
-
左外连接
-
select 字段列表 from 表1 left [ outer ] join 表2 on 条件 ...;
-
相当于查询表1(左表)的所有数据 包含 表1和表2交集部分的数据.
-
-
右外连接
-
select 字段列表 from 表1 right [ outer ] join 表2 on 条件 ...;
-
相当于查询表2(右表)的所有数据 包含 表1和表2交集部分的数据.
-
-- 外连接演示
-- 1. 查询emp表的所有数据, 和对应的部门信息(左外连接)
-- 表结构: emp,dept
-- 连接条件: emp.dept_id = dept.id
select e.*,d.name from emp e left outer join dept d on e.dept_id = d.id;
-- outer可以省略
select e.*,d.name from emp e left join dept d on e.dept_id = d.id;
-- 2. 查询emp表的所有数据, 和对应的部门信息(右外连接)
-- 表结构: emp,dept
-- 连接条件: emp.dept_id = dept.id
select d.*,e.* from emp e right outer join dept d on e.dept_id = d.id;
自连接
select 字段列表 from 表A 别名A JOIN 表A 别名B ON 条件 ... ;
- 自连接查询, 可以是内连接查询, 也可以是外连接查询.
-- 自连接
-- 1. 查询员工 及其 所属领导的名字
-- 表结构: emp
select a.name , b.name from emp a , emp b where a.managerid = b.id;
-- 2. 查询所有员工 emp 及其领导的名字 emp , 如果员工没有领导, 也需要查询出来.
-- 表结构: emp a , emp b
select a.name '员工' , b.name '领导' from emp a left join emp b on a.managerid = b.id;
子查询
-
概念: SQL语句中嵌套select语句, 称为嵌套查询, 又称子查询.
-
语法:
select * from t1 where columnl = (select column1 from t2);
子查询外部的语句可以是insert/update/delete/select的任何一个.
-
根据子查询结果不同分类:
-
标量子查询(子查询结果为单个值)
-
列子查询(子查询结果为一列)
-
行子查询(子查询结果为一行)
-
表子查询(子查询结果为多行多列)
-
根据子查询位置分类:
-
where之后
-
from之后
-
select之后
标量子查询
- 子查询返回的结果是单个值 (数字, 字符串, 日期等) , 最简单的形式 , 这种子查询成为标量子查询.
- 常用的操作符:
= , <> , > , >= , < , <=
-- 标量子查询
-- 1. 查询 "销售部" 所有的员工信息;
-- (1) 查询 "销售部" 部门ID.
# select id from dept where name = '销售部';
-- (2) 根据销售部部门ID, 查询员工信息.
# select * from emp where dept_id = 4
-- 合并就是:
select * from emp where dept_id = (select id from dept where name = '销售部');
-- 2. 查询在'方东白'入职之后的员工信息;
-- (1) 查询 "方东白" 的入职日期.
# select entrydate from emp where name = '方东白';
-- (2) 查询指定入职日期之后入职的员工信息
# select * from emp where entrydate > '2009-02-12';
-- 合并就是:
select * from emp where entrydate > (select entrydate from emp where name = '方东白');
列子查询
- 子查询返回的结果是一列(可以是多行) , 这种子查询称为列子查询.
- 常用的操作符:
in , not in , any , some , all
;
操作符 | 描述 |
---|---|
IN | 在指定的集合范围之内, 多选一. |
NOT IN | 不在指定的集合范围之内. |
ANY | 子查询返回列表中, 有任意一个满足即可. |
SOME | 与ANY等同, 使用SOME的地方都可以使用ANY. |
ALL | 子查询返回列表的所有值都必须满足. |
-- 列子查询
-- 1. 查询 "销售部" 和 "市场部" 的所有员工信息.
-- (1) 查询 "销售部" 和 "市场部" 的部门ID
# select id from dept where name = '销售部' or name = '市场部';
-- (2) 根据部门ID, 查询员工信息
# select * from emp where dept_id in (2,4);
-- 合并就是:
select * from emp where dept_id in (select id from dept where name = '销售部' or name = '市场部');
-- 2. 查询比财务部所有人工资都高的员工信息.
-- (1) 查询所有 财务部 人员工资
#select salary from emp where dept_id = (select id from dept where name = '财务部');
-- (2) 查询比 财务部 所有人员工资都高的员工信息
select * from emp where salary > all (select salary from emp where dept_id = (select id from dept where name = '财务部'));
-- 3. 查询比研发部其中任意一人工资高的员工信息.
-- (1) 查询所有 研发部 人员工资
#select salary from emp where dept_id = (select id from dept where name = '研发部');
-- (2) 查询比 研发部 任意一人工资高的员工信息
select * from emp where salary > any (select salary from emp where dept_id = (select id from dept where name = '研发部'));
行子查询
- 子查询返回的结果是一行(可以是多列) , 这种子查询称为行子查询 .
- 常用的操作符 :
= , <> , in , not in
-- 行子查询
-- 查询与 "张无忌" 的薪资及直属领导相同的员工信息.
-- (1) 查询 "张无忌" 的薪资和直属领导.
select salary, managerid from emp where name = '张无忌';
-- (2) 查询与 "张无忌" 的薪资及直属领导相同的员工信息.
select * from emp where (salary,managerid) = (12500,1);
-- 合并:
select * from emp where (salary,managerid) = (select salary, managerid from emp where name = '张无忌');
表子查询
- 子查询返回的结果是多行多列, 这种子查询称为表子查询.
- 常用的操作符:
IN
-- 表子查询
-- 1. 查询与 "鹿杖客" , "宋远桥" 的职位和薪资相同的员工信息.
-- (1) 查询 "鹿杖客" , "宋远桥" 的职位和薪资.
select job , salary from emp where name = '鹿杖客' or name = '宋远桥';
-- (2) 查询与 "鹿杖客" , "宋远桥" 职位和薪资相同的员工信息.
select * from emp where (job,salary) in (select job , salary from emp where name = '鹿杖客' or name = '宋远桥');
-- 2. 查询入职日期是 "2006-01-01" 之后的员工信息 , 及其部门信息.
-- (1) 查询入职日期是 '2006-01-01' 之后的员工信息.
select * from emp where entrydate > '2006-01-01';
-- (2) 查询这部分员工对应的 部门信息
select e.*,d.* from (select * from emp where entrydate > '2006-01-01') e left join dept d on e.dept_id = d.id;
联合查询
-
对于union查询, 就是把多次查询的结果合并起来, 形成一个新的查询结果集.
-
select 字段列表 from 表A ...
union [all]
select 字段列表 from 表B ...;
-
对于联合查询的多张表的列数必须保持一致,字段类型也需要保持一致
-
union all 会将全部的数据直接合并在一起,union 会对合并之后的数据去重
-- union all , union
-- 1. 将薪资低于 5000 的员工 , 和年龄大于 50 岁的员工全部查询出来.
select * from emp where salary < 5000
union all
select * from emp where age > 50;
-- 对结果进行去重, 不要all
select * from emp where salary < 5000
union
select * from emp where age > 50;
多表查询案例
-- 根据需求,完成SQL语句的编写
create table salgrade(
grade int,
losal int,
hisal int
) comment '薪资等级表';
insert into salgrade values (1,0,3000);
insert into salgrade values (2,3001,5000);
insert into salgrade values (3,5001,8000);
insert into salgrade values (4,8001,10000);
insert into salgrade values (5,10001,15000);
insert into salgrade values (6,15001,20000);
insert into salgrade values (7,20001,25000);
insert into salgrade values (8,25001,30000);
-- 1. 查询员工的姓名、年龄、职位、部门信息. (隐式内连接)
-- 表: emp , dept
-- 连接条件: emp.dept_id = dept.id
select e.name , e.age , e.job , d.name from emp e , dept d where e.dept_id = d.id;
-- 2. 查询年龄小于30岁的员工姓名、年龄、职位、部门信息. (显式内连接)
-- 表: emp , dept
-- 连接条件: emp.dept_id = dept.id
select e.name , e.age , e.job , d.name
from emp e inner join dept d on e.dept_id = d.id where e.age < 30;
-- 3. 查询拥有员工的部门ID、部门名称。
-- 表: emp , dept
-- 连接条件: emp.dept_id = dept.id
select distinct d.id , d.name
from emp e ,
dept d
where e.dept_id = d.id;
-- 4. 查询所有年龄大于40岁的员工,及其归属的部门名称 ; 如果员工没有分配部门,也需要展示出来
-- 表: emp , dept
-- 连接条件: emp.dept_id = dept.id
-- 外连接
select e.* , d.name
from emp e left join dept d on e.dept_id = d.id where e.age > 40;
-- 5. 查询所有员工的工资等级
-- 表: emp , salgrade
-- 连接条件: emp.salary >= salgrade.losal and emp.salary <= salgrade.hisal
select e.* , s.grade , s.losal , s.hisal
from emp e,
salgrade s
where e.salary >= s.losal and e.salary <= s.hisal;
-- 也可以使用 between and
-- select e.* , s.grade , s.losal , s.hisal from emp e, salgrade s where e.salary between s.losal and s.hisal;
-- 6. 查询 “研发部” 所有员工的信息及工资等级
-- 表: emp , salgrade , dept
-- 连接条件: emp.salary between salgrade.losal and salgrade.hisal , emp dept_id = dept.id
-- 查询条件: dept.name = "研发部"
select e.* , s.grade
from emp e ,
dept d ,
salgrade s
where e.dept_id = d.id
and ( e.salary between s.losal and s.hisal )
and d.name = '研发部';
-- 7. 查询 “研发部” 员工的平均工资
-- 表: emp , dept
-- 连接条件: emp dept_id = dept.id
select avg(e.salary) from emp e, dept d where e.dept_id = d.id and d.name = '研发部';
-- 8. 查询工资比“灭绝"高的员工信息。
-- (1) 查询 "灭绝"的薪资
select salary from emp where name = '灭绝';
-- (2) 查询比她工资高的员工数据
select * from emp where salary > (select salary from emp where name = '灭绝');
-- 9. 查询比平均薪资高的员工信息。
-- (1) 查询员工的平均薪资
select avg(salary) from emp;
-- (2) 查询比平均薪资高的员工信息
select * from emp where salary > (select avg(salary) from emp);
-- 10.查询低于本部门平均工资的员工信息。
-- (1) 查询指定部门平均薪资
select avg(e1.salary) from emp e1 where e1.dept_id = 1;
select avg(e1.salary) from emp e1 where e1.dept_id = 2;
-- (2) 查询低于本部门平均工资的员工信息
select * from emp e2 where e2.salary < ( select avg(e1.salary) from emp e1 where e1.dept_id = e2.dept_id);
-- 11.查询所有的部门信息,并统计部门的员工人数。
select d.id , d.name , (select count(*) from emp e where e.dept_id = d.id ) '人数' from dept d;
-- 12.查询所有学生的选课情况,展示出学生名称,学号,课程名称.
-- 表: student , course , student_course
-- 连接条件: student.id = student_course.studentid , course.id = student_course.courseid
select s.name , s.no , c.name from student s , student_course sc , course c where s.id = sc.studentid and sc.courseid = c.id;
事务
- 事务是一组操作的集合, 它是一个不可分割的工作单位, 事务会把所有的操作作为一个整体一起向系统提交或撤销操作请求, 即这些操作要么同时成功, 要么同时失败.
- 默认MySQL的事务是自动提交的, 也就是说 , 当执行一条DML语句 , MySQL会立即隐式的提交事务.
事务操作
方式一:
-
查看/设置事务提交方式
select @@autocommit;
(自动提交)set @@autocommit = 0;
(设置为手动提交) -
提交事务
commit;
-
回滚事务
rollback;
方式二:
-
开启事务
start transaction;
或begin;
-
提交事务
commit;
-
回滚事务
rollback;
-- 数据准备
create table account(
id int auto_increment primary key comment '主键ID',
name varchar(10) comment '姓名',
money int comment '余额'
) comment '账户表';
insert into account(id,name,money) VALUES (null,'张三',2000),(null,'李四',2000);
-- 恢复数据
update account set money = 2000 where name = '张三' or name = '李四';
select @@autocommit;
-- 设置为手动提交
set @@autocommit = 0;
-- 设置为自动提交
-- set @@autocommit = 1;
-- 方式1
-- 转账操作 (张三给李四转账1000)
-- (1). 查询张三账户的余额
select * from account where name = '张三';
-- (2). 将张三账户余额-1000
update account set money = money - 1000 where name = '张三';
-- (3). 将李四账户余额+1000
update account set money = money + 1000 where name = '李四';
-- 提交事务
commit;
-- 回滚事务
rollback;
-- 也就是说, 转账操作正常执行的时候, 最后会提交事务;
-- 如果转账操作遇见异常, 最后会执行回滚事务.
-- 方式二
-- 转账操作 (张三给李四转账1000)
start transaction;
-- (1). 查询张三账户的余额
select * from account where name = '张三';
-- (2). 将张三账户余额-1000
update account set money = money - 1000 where name = '张三';
-- (3). 将李四账户余额+1000
update account set money = money + 1000 where name = '李四';
-- 提交事务
commit;
-- 回滚事务
rollback;
事务四大特性
- 原子性(Atomicity) : 事务是不可分割的最小操作单元,要么全部成功,要么全部失败。
- 一致性(Consistency) : 事务完成时,必须使所有的数据都保持一致状态.
- 隔离性(lsolation) : 数据库系统提供的隔离机制,保证事务在不受外部并发操作影响的独立环境下运行.
- 持久性(Durability) : 事务一旦提交或回滚,它对数据库中的数据的改变就是永久的。
并发事务问题
- 脏读 : 一个事务读到另外一个事务还没有提交的数据 .
- 不可重复读 : 一个事务先后读取同一条记录,但两次读取的数据不同,称之为不可重复读 .
- 幻读 : 一个事务按照条件查询数据时,没有对应的数据行,但是在插入数据时,又发现这行数据已经存在,好像出现了"幻影".
事务隔离级别
隔离级别 | 脏读 | 不可重复读 | 幻读 |
---|---|---|---|
Read uncommitted | √ | √ | √ |
Read committed | × | √ | √ |
Repeatable Read(默认) | × | × | √ |
Serializable | × | × | × |
-
查看事务隔离级别
select @@transaction_isolation;
-
设置事务隔离级别
set [session | global] transaction isolation level {read uncommitted | read committed | repeatable read | serializable}
-- 查看事务隔离级别
select @@transaction_isolation;
-- 设置事务隔离级别
set session transaction isolation level read uncommitted;