项目开发中,在进行数据库表结构设计时,会根据业务需求及业务模块之间的关系,分析并设计表结构,由于业务之间相互关联,所以各个表结构之间也存在着各种联系,基本上分为三种:

对应的SQL脚本: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, '殷天正', '2000100103'),
(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,
student_id int not null comment '学生id',
course_id int not null comment '课程id',
constraint fk_courese_id foreign key (course_id) references course(id),
constraint fk_student_id foreign key (student_id) 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);
1). 删除之前 emp, dept表的测试数据
2). 执行如下脚本,创建emp表与dept表并插入测试数据
drop table if exists emp;
drop table if exists dept;
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, '总经办'), (6, '人事部');
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',
constraint fk_emp_dept_id foreign key (dept_id) references dept(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),
(7, '灭绝', 60, '财务总监',8500, '2002-09-12', 1,3),
(8, '周芷若', 19, '会计',48000, '2006-06-02', 7,3),
(9, '丁敏君', 23, '出纳',5250, '2009-05-13', 7,3),
(10, '赵敏', 20, '市场部总监',12500, '2004-10-12', 1,2),
(11, '鹿杖客', 56, '职员',3750, '2006-10-03', 10,2),
(12, '鹤笔翁', 19, '职员',3750, '2007-05-09', 10,2),
(13, '方东白', 19, '职员',5500, '2009-02-12', 10,2),
(14, '张三丰', 88, '销售总监',14000, '2004-10-12', 1,4),
(15, '俞莲舟', 38, '销售',4600, '2004-10-12', 14,4),
(16, '宋远桥', 40, '销售',4600, '2004-10-12', 14,4),
(17, '陈友谅', 42, null,2000, '2011-10-12', 1,null);
多表查询就是指从多张表中查询数据,
原来查询单表数据,执行的SQL形式为:select * from emp;
那么我们要执行多表查询,就只需要使用逗号分隔多张表即可,如: select * from emp , dept 
结果是员工表emp所有的记录与部门表dept所有记录的所有组合情况,这种现象称之为笛卡尔积。
笛卡尔积: 笛卡尔乘积是指在数学中,两个集合A集合 和 B集合的所有组合情况。

在SQL语句中,我们可以给多表查询加上连接查询的条件即可。因为我们这里的外键为emp.dept_id,主键是dept.id,
所以执行select * from emp , dept where emp.dept_id = dept.id;,就可以保留我们想要的结果了。
而由于id为17的员工没有dept_id字段值,所以不存在emp.dept_id = dept.id的条件,所以没有查询到他。

内连接查询的是两张表的交集部分。
内连接的语法分为两种: 隐式内连接、显式内连接。先来学习一下具体的语法结构。
SELECT 字段列表 FROM 表1 , 表2 WHERE 条件 ... ;(上面的例子)
SELECT 字段列表 FROM 表1 [ INNER ] JOIN 表2 ON 连接条件 ... ;
select emp.name,dept.name from emp, dept where emp.dept_id = dept.id;select e.name '姓名',d.name '部门' from emp as e, dept as d where e.dept_id = d.id;INNER JOIN ... ON ...select e.name, d.name from emp e inner join dept d on e.dept_id = d.id; orselect 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(左表)的所有数据,当然也包含表1和表2交集部分的数据。
SELECT 字段列表 FROM 表1 RIGHT [ OUTER ] JOIN 表2 ON 条件 ... ;
右外连接相当于查询表2(右表)的所有数据,当然也包含表1和表2交集部分的数据。
查询emp表的所有数据, 和对应的部门信息
由于需求中提到,要查询emp的所有数据,所以是不能内连接查询的,需要考虑使用外连接查询。
·表结构: emp, dept
·连接条件: emp.dept_id = dept.id
select e.*, d.name from emp e left join dept d on e.dept_id = d.id;

查询dept表的所有数据, 和对应的员工信息(右外连接)
由于需求中提到,要查询dept表的所有数据,所以是不能内连接查询的,需要考虑使用外连接查
询。
·表结构: emp, dept
·连接条件: emp.dept_id = dept.id
select e.*, d.name from emp e right join dept d on e.dept_id = d.id;
or(将右外连接写成左外连接)
select e.*, d.name from dept d left join emp e on e.dept_id = d.id;

注意事项:
左外连接和右外连接是可以相互替换的,只需要调整在连接查询时SQL中,表结构的先后顺
序就可以了。而我们在日常开发使用时,更偏向于左外连接。
自连接查询,顾名思义,就是自己连接自己,也就是把一张表连接查询多次。我们先来学习一下自连接的查询语法:
SELECT 字段列表 FROM 表A 别名A JOIN 表A 别名B ON 条件 ... ;
而对于自连接查询,可以是内连接查询,也可以是外连接查询。
查询员工 及其 所属领导的名字
·表结构: emp
思路:因为managerid就是id对应的人,所以我们将emp表复制一份,变为表a和表b,其中表a的id为主键,表b的managerid为外键,此时我们就可以使用连接查询了。
select a.name , b.name from emp a , emp b where a.managerid = b.id;(内连接)
查询所有员工 emp 及其领导的名字 emp , 如果员工没有领导, 也需要查询出来
·表结构: emp
select a.name '员工', b.name '领导' from emp a left join emp b on a.managerid = b.id;(外连接)
注意事项:
在自连接查询中,必须要为表起别名,要不然我们不清楚所指定的条件、返回的字段,到底
是哪一张表的字段。
对于union查询,就是把多次查询的结果合并起来,形成一个新的查询结果集。
SELECT 字段列表 FROM 表A ...
UNION [ ALL ]
SELECT 字段列表 FROM 表B ....;
select * from emp where salary < 5000
union all
select * from emp where age > 50;
select * from emp where salary < 5000
union
select * from emp where age > 50;
注意
- 对于联合查询的多张表的列数必须保持一致,字段类型也需要保持一致。
- union all 会将全部的数据直接合并在一起,union 会对合并之后的数据去重。
SELECT * FROM t1 WHERE column1 = ( SELECT column1 FROM t2 );子查询返回的结果是单个值(数字、字符串、日期等),最简单的形式,这种子查询称为标量子查询。
常用的操作符:= ,<>/!=, >, >=, <, <=
查询 “销售部” 的所有员工信息
完成这个需求时,我们可以将需求分解为两步:
①. 查询 “销售部” 部门ID
②. 根据 “销售部” 部门ID, 查询员工信息
select * from emp where dept_id = (select id from dept where name = '销售部');(这里子查询返回的只有一个值,所以叫标量子查询)
查询在 “方东白” 入职之后的员工信息
完成这个需求时,我们可以将需求分解为两步:
①. 查询 方东白 的入职日期
②. 查询指定入职日期之后入职的员工信息
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 | 子查询返回列表的所有值都必须满足 |
select * from emp where dept_id in (select id from dept where name = '销售部' or name = '市场部');
查询比 财务部 所有人工资都高的员工信息
分解为以下两步:
①. 查询所有 财务部 人员工资
②. 比 财务部 所有人工资都高的员工信息
这里有一个数据出错了,修改一下:update emp set salary = 4800 where salary = 48000;
select * from emp where salary > all (select salary from emp where dept_id = (select id from dept where name = '财务部'));
查询比研发部其中任意一人工资高的员工信息
分解为以下两步:
①. 查询研发部所有人工资
②. 比 研发部 其中任意一人工资高的员工信息
select * from emp where salary > any (select salary from emp where dept_id = (select id from dept where name = '研发部'));
select * from emp where salary > some (select salary from emp where dept_id = (select id from dept where name = '研发部'));
子查询返回的结果是一行(可以是多列),这种子查询称为行子查询。
常用的操作符:= 、<>/!= 、IN 、NOT IN
select * from emp where (salary,managerid) = (select salary,managerid from emp where name = '张无忌') ;子查询返回的结果是多行多列,这种子查询称为表子查询。
常用的操作符:IN
查询与 “鹿杖客” , “宋远桥” 的职位和薪资相同的员工信息
分解为两步执行:
①. 查询 “鹿杖客” , “宋远桥” 的职位和薪资
②. 查询与 “鹿杖客” , “宋远桥” 的职位和薪资相同的员工信息
select * from emp where (job, salary) in (select job, salary from emp where name = '鹿杖客' or name = '宋远桥');
查询入职日期是 “2006-01-01” 之后的员工信息 , 及其部门信息
分解为两步执行:
①. 入职日期是 “2006-01-01” 之后的员工信息
②. 查询这部分员工, 对应的部门信息
select e.*, d.name from (select * from emp where entrydate > '2006-01-01') e left join dept d on e.dept_id = d.id;
create table salgrade(
grade int,
losal int,
hisal int
) comment '薪资等级表';
insert into salgrade values (1,0,3000), (2,3001,5000),
(3,5001,8000), (4,8001,10000),
(5,10001,15000), (6,15001,20000),
(7,20001,25000), (8,25001,30000);
在这个案例中,我们主要运用上面所讲解的多表查询的语法,完成以下的12个需求即可,方法不唯一。这里主要涉及到的表就三张:emp员工表、dept部门表、salgrade薪资等级表 。
查询员工的姓名、年龄、职位、部门信息 (隐式内连接)
表: emp , dept
连接条件: emp.dept_id = dept.id
select e.name, e.age, e.job, d.name from emp e left join dept d on e.dept_id = d.id;
查询年龄小于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; 根据sql的执行顺序,应该是先根据连接条件将两张表连接然后再根据where后的条件返回最终结果。
查询拥有员工的部门ID、部门名称
表: emp , dept
连接条件: emp.dept_id = dept.id
select distinct d.* from emp e, dept d where e.dept_id = d.id;,如果觉得难理解,可以想象内连接其实本质是从笛卡尔积的结果中根据条件筛选出的结果,那么如果一个部门没有员工,就不可能存在e.dept_id = d.id这样的条件,所以直接就可以得到正确结果了。
这三个都是内连接问题,也充分体现了内连接得到的是两个表的交集结果。
查询所有年龄大于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;
查询所有员工的工资等级
表: emp , salgrade
连接条件 : emp.salary >= salgrade.losal and emp.salary <= salgrade.hisal
select e.*, s.* from emp e left join salgrade s on e.salary between s.losal and s.hisal;
查询 “研发部” 所有员工的信息及 工资等级
表: emp , salgrade , dept
连接条件 : emp.salary between salgrade.losal and salgrade.hisal , emp.dept_id = dept.id
查询条件 : dept.name = ‘研发部’
select e.*, d.name, 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 = '研发部';
查询 “研发部” 员工的平均工资
表: emp , dept
连接条件 : emp.dept_id = dept.id
select d.name, avg(e.salary) from emp e left join dept d on d.id = e.dept_id where d.name = '研发部';
查询工资比 “灭绝” 高的员工信息。
①. 查询 “灭绝” 的薪资
②. 查询比她工资高的员工数据
select * from emp where salary > (select salary from emp where name = '灭绝');
查询比平均薪资高的员工信息
①. 查询员工的平均薪资
②. 查询比平均薪资高的员工信息
select * from emp where salary > (select avg(salary) from emp);
查询低于本部门平均工资的员工信息
①. 查询指定部门平均薪资
②. 查询低于本部门平均工资的员工信息
select *, (select avg(salary) from emp e1 where e1.dept_id = e2.dept_id) '平均薪资' from emp e2 where e2.salary < (select avg(salary) from emp e1 where e1.dept_id = e2.dept_id);
查询所有的部门信息, 并统计部门的员工人数
select dept.*, (select count(*) from emp where emp.dept_id = dept.id ) '人数' from dept;
查询所有学生的选课情况, 展示出学生名称, 学号, 课程名称
表: student , course , student_course
连接条件: student.id = student_course.studentid , course.id =
student_course.courseid
select t.name, t.no, c.name from (select s.*, sc.course_id from student s left join student_course sc on s.id = sc.student_id) t left join course c on c.id = t.course_id;
事务 是一组操作的集合,它是一个不可分割的工作单位,事务会把所有的操作作为一个整体一起向系统提交或撤销操作请求,即这些操作要么同时成功,要么同时失败。
比如: 张三给李四转账1000块钱,张三银行账户的钱减少1000,而李四银行账户的钱要增加1000。 这一组操作就必须在一个事务的范围内,要么都成功,要么都失败。
注意: 默认MySQL的事务是自动提交的,也就是说,当执行完一条DML语句(对数据的增删改)时,MySQL会立即隐式的提交事务,所以我们必须手动开辟事务。
drop table if exists account;
create table account
(
id int primary key AUTO_INCREMENT comment 'ID',
name varchar(10) comment '姓名',
money double(10, 2) comment '余额'
) comment '账户表';
insert into account(name, money)
VALUES ('张三', 2000),
('李四', 2000);
正常情况
select * from account where name = '张三';
update account set money = money - 1000 where name = '张三';
update account set money = money + 1000 where name = '李四';
update account set money = 2000 where name = '张三' or name = '李四';
非正常情况
#把下面的语句作为一个整体执行,报错后,数据就会出现我们解释的错误情况
update account set money = money - 1000 where name = '张三';
update account set money = money + 1000 where;
SELECT @@autocommit ; 
SET @@autocommit = 0 ; 1为自动提交,0为手动提交COMMIT;ROLLBACK;注意:上述的这种方式,我们是修改了事务的自动提交行为, 把默认的自动提交修改为了手动提
交, 此时我们执行的DML语句都不会提交, 需要手动的执行commit进行提交。
update account set money = 2000 where name = '张三' or name = '李四';
set @@autocommit = 0;
update account set money = money - 1000 where name = '张三';
update account set money = money + 1000 where name = '李四';
select * from account;
这时虽然输出是发生了改变(可以理解为我们申请了一个事务,我们现在都是直接对这个事务操作,而不是直接对数据库操作)

但是我们打开DataGrip的数据库刷新后查看会发现并没有发生改变。

所以需要我们提交事务
commit

update account set money = money - 1000 where name = '张三';
commit;
set @@autocommit = 0;
update account set money = money - 1000 where name = '张三';
update account set money = money + 1000 where;
执行上面的代码,程序会报错,这时我们知道数据库没有变化,但是我们申请的事务发生了改变(因为我们让张三的钱减少了1000,只不过没去修改数据库的数据)。

这时,我们因为办理事务的过程中出现了问题,所以想要让这个事务回到最开始模样,那么我们就可以执行回滚事务:
rollback;

START TRANSACTION 或 BEGIN ;COMMIT;ROLLBACK;set @@autocommit = 1;
update account set money = 2000 where name = '张三' or name = '李四';
start transaction;
update account set money = money - 1000 where name = '张三';
update account set money = money + 1000 where name = '李四';
commit;
update account set money = 2000 where name = '张三' or name = '李四';
start transaction;
update account set money = money - 1000 where name = '张三';
update account set money = money + 1000 where name = '李四';
rollback;
上述就是事务的四大特性,简称ACID。
事务A对数据进行了更新后,事务B读取到了事务A未提交的数据。

事务A进行了1操作后,事务B对数据进行了更新,这时事务A进行2操作时读取到的数据不相同。

事务A在查询数据时发现没有,然后准备插入,但是在事务A插入之前事务B就插入了数据。
| 隔离级别 | 脏读 | 不可重复读 | 幻读 |
|---|---|---|---|
| Read uncommitted(读未提交) | √ | √ | √ |
| Read committed(读已提交) | × | √ | √ |
| Repeatable Read(默认,可重复读) | × | × | √ |
| Serializable(串行化) | × | × | × |
SELECT @@TRANSACTION_ISOLATION;
SET [ SESSION | GLOBAL ] TRANSACTION ISOLATION LEVEL {READ UNCOMMITTED | READ COMMITTED | REPEATABLE READ | SERIALIZABLE };
SESSION 是会话级别,表示只针对当前会话有效,GLOBAL 表示对所有会话有效
这里开启两个客户端来展示,相当于两个事务。
打开第一个客户端输入
set session transaction isolation level read uncommitted;
start transaction;
select * from account;
然后打开第二个客户端输入:
start transaciton;
update account set money = money - 1000 where name = '张三';
这时在第一个客户端重新select会发现数据已经发生改变
也就是说第一个事务读到了第二个事务没有提交的数据,可以看到是存在脏读问题的。
最后提交一下事务:commit,再打开第一个客户端select看到数据发生了变化,也就是存在的不可重复读问题。
这时如果在第二个客户端进行了数据插入,第一个客户端也会读取到这个数据插入,想要插入相同的数据id就会出现幻读问题。
前面的执行顺序和上面一样,
最后在第二个客户端提交了事务以后,可以在第一个客户端select看到数据发生了变化,这就是不可重复读问题。
也就是说第一个客户端事务只读已经提交的数据,在第二个客户端没有提交事务之前,第一个客户端读取不到第二个客户端对数据库做的更新操作。
这时如果在第二个客户端进行了数据插入并提交,第一个客户端已经看到了这个变化,所以在插入相同的数据id就也会出现幻读问题。
打开第一个客户端输入
set session transaction isolation level repeatable read;
start transaction;
select * from account;
然后打开第二个客户端输入:
start transaciton;
update account set money = money - 1000 where name = '张三';
commit;
这时第一个客户端输入select会看到数据没有受到第二个客户端事务引起的变化,当第一个客户端的事务提交(commit)了以后,再输入select才可以读取到事务的变化,也就没有不可重复读的问题了。
但是在第二个客户端插入了数据并提交后,所以第一个客户端查不到这个数据,但是插入数据的时候仍然会报错,像一种幻觉,也就是幻读问题。
这里只讲插入数据的情况,
打开第一个客户端输入
set session transaction isolation level repeatable read;
start transaction;
select * from account;
然后打开第二个客户端输入:
start transaciton;
insert account(id) values(4);
会发现光标一直在闪,说明程序堵塞了,
就是因为它在等待第一个事务提交(优先级较低),当把第一个事务提交,这里就会看到程序继续运行了,也就避免了幻读的问题。
这就是串行化的特点,一次只能由一个事务操作,只有当一个事务提交了之后,下一个事务才能继续操作。