数据库MySQL基础篇

1.SQL-DDL

目录

1.SQL-DDL

1.1数据库操作

1.2表操作

 1.2.1 创建&查询

 1.2.2 数据类型

1.2.3 修改&删除

2.SQL-DML

2.1 insert

 2.2 modify

2.3 delete

3.SQL-DQL

3.1 基本查询

3.2 条件查询

3.3 聚合函数

3.4 分组查询

3.5 排序查询

3.6 分页查询

3.7 执行顺序

4.SQL-DCL

4.1 管理用户

 4.2 权限控制

5.函数

5.1 字符串函数

5.2 数值函数

5.3 日期函数

5.4 流程函数

6.约束

 6.1 外键约束

7.多表查询

7.1 多表关系

7.1.1 一对多(多对一)

7.1.2 多对多

7.1.3 一对一

7.2 多表查询概述

7.3 内连接

7.4 外连接

7.5 自连接

7.6 子查询

7.6.1 标量子查询

7.6.2 列子查询 

7.6.3 行子查询

7.6.4 表子查询

7.7 联合查询

8.事务

8.1 事务操作

 8.2 事务隔离级别

8.2.1 脏读

8.2.2 不可重复读

​编辑 8.2.3 幻读


1.1数据库操作

  • 查询

        查询所有数据库: show databases;

        查询当前数据库: select database();

  • 创建

        create database 数据库名称 [default charset 字符集] [collate 排序规则];

        (中括号的可以省略)

  • 删除

        drop database 数据库名称;

  • 使用

        use 数据库名称;

1.2表操作

  • 查询当前数据库所有表

        show tables;

  • 查询表结构

        dese 表名称;

  • 查询指定表的建表语句

        show create table 表名称;

 1.2.1 创建&查询

图片来自黑马程序员

 1.2.2 数据类型

主要分为:数值类型、字符串类型、日期时间类型

char(长度)        性能好

varchar(长度)      性能较差(需要根据内容计算空间)

 图片来自黑马程序员

1.2.3 修改&删除

  • 添加字段

        alter table 表名 add 字段名 类型(长度)[comment 注释] [约束]

  • 修改字段

        修改数据类型:

                alter table 表名 modify 字段名 新数据类型(长度)

        修改字段名和字段类型:

                alter table 表名 change 旧字段名 新字段名 类型(长度)[comment 注释] [约束];

         删除字段

                alter table 表名 drop 字段名;

  • 修改表名

        alter table 表名 rename to 新表名

  • 删除表

        drop table 表名;

  • 删除指定表并重新创建该表

        truncate table 表名;

2.SQL-DML

Data Manipulation Language(数据操作语言) ,用来对数据库中表的数据进行增删改操作

  • 添加数据(insert)
  • 修改数据(update)
  • 删除数据(delete)

2.1 insert

  •  给指定字段添加数据

        insert into 表名(字段名1,字段名2,...) values (值1,值2,...);

  • 给全部字段添加数据

        insert into 表名 values(值1,值2,....);

  • 批量添加数据

        insert into 表名(字段名1,字段名2,...) values (值1,值2,...),(值1,值2,...);

        insert into 表名 values (值1,值2,...),(值1,值2,...);//为当前表中所有字段赋值

注意:

        插入数据时,指定的字段顺序需要与值的顺序是一一对应的

        字符串和日期类型数据应该包含在引导中

        插入的数据大小,应该再字段的规定范围内

 2.2 modify

修改数据

        update 表名 set 字段名1 = 值1,字段名2 = 值2,...[where 条件];

如果更新时不加where条件,则会修改整张表指定字段的所有数据

2.3 delete

 删除数据

        delete from 表名 [where 条件]

如果删除时不加where条件,则会删除整张表的所有数据

3.SQL-DQL

Data Query Language(数据查询语言),用来查询数据库中表的记录

  • 基本查询

                select

                        字段列表

                from

                        表名查询

  • 条件查询

                where

                        条件列表

  • 聚合函数

                count、max、min、avg、sum

  • 分组查询    

                group by

                        分组字段列表

                having

                        分组后条件列表

  • 排序查询 

                order by

                        排序字段列表

  • 分页查询

                limit

                        分页参数

以上顺序也为编写顺序

3.1 基本查询

  1. 查询多个字段        
    1. select 字段1,字段2,字段3,... ,from 表名;
    2. select * from 表名;
  2. 设置别名
    1. select 字段1 [AS 别名1],字段2[AS 别名2] ... from 表名;
  3. 去除重复记录
    1. select distinct 字段列表 from 表名; 
-- 查询指定字段
 select name,workno,age from employ;

-- 查询所有字段返回
select * from employ;

-- 查询所有员工工作地址
select employ.workaddress from employ;

-- 起别名
select employ.workaddress as '工作地址' from employ;
select employ.workaddress '工作地址' from employ;

-- 不重复
select distinct employ.workaddress from employ;


-- 查询年龄等于88
select * from employ where age = 66;

3.2 条件查询

  1. 语法
    1. select 字段列表 from 表名 where 条件列表;
  2. 条件
-- 年龄小于20
select *from employ where age <= 40;

-- 查询没有身份中号
select *
from employ where idchar is null;

--  不等于  !=  或者  <>
select *
from employ where age != 66;

--  and  或者  &&
select *
from employ where age >= 15 and age <= 20;

select *
from employ where age between 15 and 20;

-- and
select *
from employ where gender = '女' and age < 20;

-- or  或者   in
select *
from employ where age = 18 or age = 66;

select *
from employ where age in(18,20,66,45);

-- 查询姓名为两个字的员工
select *
from employ where name like '__';

-- 查询身份证号最后一位为X(%代表不管前面,只看最后一位)
select *
from employ where idchar like '%X';

select *
from employ where name like '范__';

3.3 聚合函数

将一列数据作为一个整体,进行纵向计算

语法

select 聚合函数(字段列表)from 表名;

注:所有null值不参与聚合运算

 常用的聚合函数

 

-- idchar 的个数
select count(idchar) from employ;

-- 统计平均年龄
select avg(employ.age) from employ;

-- 找出最大年龄
select max(age) from employ;

-- 统计西安地区员工年龄之和
select avg(age)
from employ where workaddress = '西安';

3.4 分组查询

1.语法

     select 字段列表 form 表名 [where 条件] group by 分组字段名 [having 分组后过滤条件];

2.where 与 having 的区别

     执行时机不同:where是分组之前进行过滤,不满足where条件,不参与分组;

                               而having是分组之后对结果进行过滤

     判断条件不同:where不能对聚合函数进行判断,而having可以。

注意:

  • 执行顺序:where  > 聚合函数  >  having
  • 分组之后,查询的字段一般为聚合函数和分组字段,查询其他字段无意义。
-- --------------------------------------------分组查询
-- 1.根据性别分组,统计男性员工 和 女性员工的数量
select gender ,count(*)
from employ group by gender ;

-- 根据性别分组,统计男性员工和女性员工的平均年龄
select gender, avg(age) from employ group by gender ;

-- 查询年龄小于45 ,并根据工作地址进行分组  获取员工数量大于等于3 的工作地址
select workaddress,count(*) from employ where age < 45 group by workaddress having count(*) >= 3;

3.5 排序查询

1.语法

select 字段列表 from 表名 order by 字段1 排序方式1,字段二 排序方式2;

2.排序方式

asc:   升序(默认值)

desc: 降序

注:如果是多字段排序,当地一个字段值相同时,才会根据第二个字段进行排序

-- 排序查询
-- 1.根据年龄升序排序
select *
from employ order by age;

-- 降序
select *
from employ order by age desc;

-- 根据入职时间降序
select *
from employ order by enterdata desc ;

-- 根据年龄进行升序,年龄相同按照入职时间降序
select *
from employ order by age , enterdata desc ;

3.6 分页查询

1.语法

select 字段列表 from 表名 limit 起始索引,查询记录数;

注意:

  • 起始索引从0开始,起始索引 = (查询页码 - 1)* 每页显示记录数
  • 分页查询是数据库的方言,不同的数据库有不同的实现,MySQL中是LIMIT
  • 如果查询的是第一页数据,起始索引可以省略,直接简写为limit 10;
-- 分页查询
-- 1. 查询第一页员工数,每页展示10条记录
select *
from employ limit 0,10;

select *
from employ limit 10;

-- 2. 查询第二页员工数据,每页展示10条记录
select *
from employ limit 10,10;

3.7 执行顺序

 DQL编写顺序:

  1. select             字段列表
  2. from                表名查询
  3. where              条件列表             
  4. count、max、min、avg、sum   聚合函数
  5. group by          分组字段列表
  6. having             分组后条件列表
  7. order by           排序字段列表
  8. limit                 分页参数

 DQL执行顺序

  1. from          表名列表
  2. where        条件列表
  3. group by    分组字段列表
  4. having       分组后条件列表
  5. select         字段列表
  6. order by     排序字段列表
  7. limit            分页参数

4.SQL-DCL

Data Control Language(数据控制语言) 用来管理数据库,用户、控制数据库的访问权限

  1. 管理用户

4.1 管理用户

  • 查询用户

                use mysql;

                select * from user;

  • 创建用户

                create user  '用户名'@'主机名'  identified by '密码';

  • 修改用户密码

                alter user  '用户名'@'主机名'  identified with mysql_native_password by '新密码'

  • 删除用户

                drop user '用户名'@'主机名';

注:

主机名可以使用%通配(代表在所有主机上都可以使用)

这类SQL开发人员操作比较少,主要是DBA(Database Administrator 数据库管理员)使用

-- 创建用户 itcast, 只能够在当前住机localhost访问 ,密码123456;
create user 'itcast'@'localhost' identified by '123456';

-- 创建用户 heima, 可以在任意主机访问该数据库 ,密码123456
create user 'heima'@'%' identified by '123456';


-- 修改密码
alter user 'heima'@'%' identified with mysql_native_password by '1234';

select *
from user where user = 'heima';

-- 删除用户
drop user 'heima'@'%';
drop user 'itcast'@'localhost';

 4.2 权限控制

MySQL中定义很多权限,但常用的就以下几种

图片来自黑马程序员

  • 查询权限

        show grants for '用户名'@'主机名';

  • 授予权限

        grant 权限列表 on 数据库名.表名 to '用户名'@'主机名';

  • 撤销权限

        revoke 权限列表 on 数据库名.表名 from '用户名'@'主机名';

-- 查询权限
show grants for 'root'@'localhost';
show grants for 'heima'@'%';

-- 授予heima用户 有关 数据库my_first的所有权限
grant all on my_first.* to 'heima'@'%';
show grants for 'heima'@'%';

-- 撤销heima用户 有关 数据库my_first的所有权限
revoke all on my_first.* from 'heima'@'%';

5.函数

  • 字符串函数
  • 数值函数
  • 日期函数
  • 流程函数

5.1 字符串函数

MySQL中内置很多字符串函数,常用的几个如下

图片来自黑马程序员

-- concat   字符串拼接
select concat('hello' , ' mysql'); -- hellomysql

-- 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,7); -- hello M

例如:

-- 由于业务需求变更 企业员工的工号,统一为5位数,不足5为在前补零
update employ set workno = lpad(workno,5,0);

5.2 数值函数

图片来自黑马程序员

-- 数值函数
-- ceil  向上取整
select ceil(1.1); -- 2

-- floor 向下取整
select floor(1.9); -- 1

-- mod   取模
select mod(7,4); -- 3

-- rand 0-1随机数
select rand(); -- 16位小数

-- round   对2.345四舍五入,保留两位小数
select round(2.345,2); -- 2.35
-- 生成一个六位数的随机验证码
select lpad(round(rand() * 1000000,0),6,'0'); -- 095825

5.3 日期函数

图片来自黑马程序员

5.4 流程函数

流程函数也是很常用的一类函数,可以在SQL语句中实现条件筛选,从而提高语句的效率

-- 流程控制函数
-- if
 select if(false, 'OK' ,'Error'); -- Error

 -- ifnull
select ifnull('', 'Default');
select ifnull('ok', 'default');
select ifnull('null', 'asdd');
select ifnull(null, 'asddl');


 -- case
 -- 需求: 查询表中的员工姓名和工作地址(上海、北京------>一线城市,其他------>二线城市
 select
     name,
     ( case workaddress when '北京' then '一线城市' when '上海' then '一线城市' else '二线城市' end ) as '工作地址'
 from employ;

6.约束

1.概念: 约束是作用与表中字段上的规则,用于限制存储在表中的数据。

2.目的:保证数据库中数据的正确、有效性、完整性。

3.分类:

图片来自黑马程序员

 例:根据需求,完成表结构的创建

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 '用户表';

 6.1 外键约束

外键用来让两张表的数据之间建立链接,从而保证数据一致性和完整性

语法:

  • 添加外键

create table 表名(

        字段名  数据类型...

        ........

        [constraint] [外键名称] foreign key(外键字段名)  references 主表(主表列名)

);

alter table 表名 add constraint 外键名称 foreign key(外键字段名) references 主表(主表列名)

  • 删除外键

 alter table 表名 drop foreign key 外键名称 ;

-- 添加外键
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;
  •  删除/更新行为

alter table 表名 add constraint 外键名称 foreign key(外键字段) references 主表名(主表字段名) on update cascade on delete cascade;

-- 外键的删除和更新行为
alter table emp add constraint fk_emp_dept_id foreign key (dept_id) references dept(id) on update cascade on delete cascade ;

 可以在子表的修改中直接修改

7.多表查询

  • 多表关系
  • 多表查询概述
  • 内连接
  • 外连接
  • 自连接
  • 子查询

7.1 多表关系

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

  • 一对多(多对一)
    • 案例:部门 与 员工的关系
    • 关系: 一个部门对应多个员工,一个员工对应一个部门
    • 实现: 在多(员工)的一方建立外键,指向一(部门)的一方的主键
  • 多对多
    • 案例:学生 与 课程的关系
    • 关系: 一个学生可以选修多门课程,一门课程也可以被多个学生选择
    • 实现:建立第三张中间表,中间表至少包含两个外键,分别关联两方主键
  • 一对一
    • 案例:用户 与 用户详细的关系
    • 关系: 一对一关系,多用于单表拆分,将一张表的基础字段放在一张表,其他详细字段放在另一张表,以提升操作效率
    • 实现:在任意一方加入外键,关联另外以放的主键,并且设置外键为唯一的(unique)

7.1.1 一对多(多对一)

  • 案例:部门 与 员工的关系
  • 关系: 一个部门对应多个员工,一个员工对应一个部门
  • 实现: 在多(员工)的一方建立外键,指向一(部门)的一方的主键
-- 外键的删除和更新行为
alter table emp add constraint fk_emp_dept_id foreign key (dept_id) references dept(id) on update set null on delete set null ;

 

7.1.2 多对多

  • 案例:学生 与 课程的关系
  • 关系: 一个学生可以选修多门课程,一门课程也可以被多个学生选择
  • 实现:建立第三张中间表,中间表至少包含两个外键,分别关联两方主键

 创建中间表,关联两方主键

create table student_course(
    id int auto_increment primary key comment '主键',
    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);

7.1.3 一对一

  • 案例:用户 与 用户详细的关系
  • 关系: 一对一关系,多用于单表拆分,将一张表的基础字段放在一张表,其他详细字段放在另一张表,以提升操作效率
  • 实现:在任意一方加入外键,关联另外以放的主键,并且设置外键为唯一的(unique)
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 '中学',
    universityschool 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, universityschool, userid) values
                        (null,'本科','舞蹈','静安区第一小学','静安区第一中学','北京舞蹈学院',1),
                        (null,'硕士','表演','朝阳区第一小学','朝阳区第一中学','北京电影学院',2),
                        (null,'本科','英语','杭州市第一小学','杭州市第一中学','杭州师范大学',3),
                        (null,'本科','应用数学','阳泉区第一小学','阳泉区第一中学','清华大学',4);

 

7.2 多表查询概述

  • 概述:指从多张表中查询数据,
  • 笛卡尔积:笛卡尔乘积是指在数学中,两个集合A和B的所有组合情况。(在多表查询时,需要消除无效的笛卡尔积)
-- 多表查询 -- 笛卡尔积
select *
from emp,dept where emp.dept_id = dept.id;

7.3 内连接

连接查询:

        内连接:相当于查询A、B交集部分数据

  • 隐式内连接

        select 字段列表 from 表1,表2 where 条件...;

  • 显式内连接

        select 字段列表 from 表1 [inner] join 表2 on 连接条件 [where...]...;

        下划线的相当于两张表,where等其他语句都应在原来的位置

相对而言,隐式连接好理解好书写,语法简单

但是显式链接可以减少字段的扫描,有更快的执行速度,这种速度优势在3张或以上的表连接时比较明显

 隐式内连接

-- 查询每一个员工的姓名,以及关联的部门的名称(隐式内连接实现)
-- 表结构: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;

显示内连接 

-- 查询每一个员工的姓名,以及关联的部门的名称(显式式内连接实现)
-- 表结构: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;

 

7.4 外连接

连接查询

        外连接:

                左外连接:查询左表所有数据,以及两张表交集部分数据

                        select 字段列表 from 表1 left[outer] join 表2 on 条件

                右外连接:查询右表所有数据,以及两张表交集部分数据

                        select 字段列表 from 表1 right[outer] join 表2 on 条件

左外连接(包含左表 emp 的所有数据)

-- 查询emp表中所有数据,和对应的部门信息(左外连接)
-- 表结构:emp,dept
-- 连接条件:emp.dept_id = dept.id
select e.*,d.name
from emp e
left join dept d on d.id = e.dept_id;

右外连接(会包含右表 dept 的所有数据)

-- 查询emp表中所有数据,和对应的部门信息(右外连接)
-- 表结构:emp,dept
-- 连接条件:emp.dept_id = dept.id
select e.*,d.*
from emp e
right join dept d on d.id = e.dept_id;

7.5 自连接

连接查询

        自链接:当前表与自身的连接查询,自链接必须使用表别名

select 字段列表 from 表A 别名A join 表A 别名B on 条件...

自链接查询可以是内连接查询,也可以是外连接查询.

-- 自链接
-- 查询员工 及其 所属领导的名字
-- 表结构:emp
select a.name,b.name
from emp a,emp b
where a.managerid = b.id;

-- 查询所有员工 emp ,如果员工没有领导,也要查询出来(使用外连接)
select a.name , b.name
from emp a
left join emp b on a.managerid = b.id;

 外连接方式结果

 

7.6 子查询

概念:SQL语句中嵌套select够,称为嵌套查询,又称子查询

      select * from t1 where column1 = (select column from t2);

子查询外部的语句可以是insert / update / delete / select 的任何一个

根据子查询结果不同,分为:

  • 标量子查询(子查询结果为单个值)  
  • 列子查询(子查询结果为一列)
  • 行子查询(子查询结果为一行)
  • 表子查询(子查询结果为多行多列)

根据子查询位置,分为:where之后,from之后、select之后

7.6.1 标量子查询

标量子查询:

     子查询返回的结果时单个值(数字、字符串、日期等),最简单的形式,称为标量子查询

     常用操作符:=     <>     >     >=     <     <=

-- 标量子查询
-- 1 查询销售部所有员工信息
-- a 查询销售部门 部门ID
select id from dept where name = '销售部';

-- b 根据部门ID 查询员工信息
select *
from emp where dept_id = (select id from dept where dept.name = '销售部');

-- 2. 查询在 常遇春 入职之后的员工信息
-- a 查询常遇春的入职日期
select emp.entrydate from emp where name = '常遇春';

-- b 查询指定入职日期之后入职的员工信息
select *
from emp where entrydate > (select emp.entrydate from emp where name = '常遇春');

7.6.2 列子查询 

列子查询

        子查询返回的结果时一列(可以是多行),称为列子查询

常用操作符:in 、 not in 、 any 、 some 、 all

 就是简单的嵌套加 限定操作符

-- 列子查询
-- 1. 查询 销售部 和 市场部 的所有员工信息
-- a. 查询 销售部 和 市场部 的部门ID
select id from dept where name in('销售部','市场部');

-- b. 根据部门ID, 查询员工信息
select *
from emp where dept_id in(select id from dept where name in('销售部','市场部'));

-- 2. 查询比 财务部 所有人工资都高的员工信息
-- a. 查询所有财务部 人员工资
select id from dept where name = '财务部';

select emp.salary from emp where dept_id = (select id from dept where name = '财务部');

-- b.比 财务部 所有人工资都高的员工信息
select * from emp where salary > all(select emp.salary from emp where dept_id = (select id from dept where name = '财务部'));


-- 3. 查询比研发部其中任意一人员工工资高的员工信息
-- a. 查询研发部所有人工资
select id from dept where name = '研发部';

select emp.salary from emp where dept_id = (select id from dept where name = '研发部');

-- 比研发部任意一人工资高的员工信息
select *
from emp where salary > any(select emp.salary from emp where dept_id = (select id from dept where name = '研发部'));

7.6.3 行子查询

行子查询

        子查询返回的结果是一行(可以是多列) 称为行子查询

常用操作符:=、<>、in、not in

-- 行子查询
-- 1.查询与 张无忌 的薪资以及直属领导相同的员工信息
-- a, 查询 张无忌 的 薪资 以及 直属领导
select emp.salary,emp.managerid from emp where name = '张无忌';

-- b.查询与张无忌的薪资以及直属领导相同的员工信息
select *
from emp where (salary,managerid) = (select emp.salary,emp.managerid from emp where name = '张无忌');

7.6.4 表子查询

表子查询

        子查询返回的结果是多行多列,称为表子查询

常用操作符:in

-- 表子查询
-- 1.查询与 路章课 周芷若 的职位和信息相同的员工信息
-- 0.查询与 路章课 周芷若 的职位和薪资
select emp.job,emp.salary from emp where name in ('路章课' ,'周芷若');

-- b.查询与 路章课 周芷若 的职位和信息相同的员工信息
select *
from emp where (job,salary) in (select emp.job,emp.salary from emp where name in ('路章课' ,'周芷若'));


-- 2.查询入职日期 是‘2006-01-01’之后入职的员工信息
-- a. 入职日期 ‘2006-01-01’之后的员工信息
select * from emp where entrydate > '2006-01-01';

-- b.查询这部分员工,对应的部门信息
select e.*,d.*
from (select * from emp where entrydate > '2006-01-01') e
left join dept d on e.dept_id = d.id;

7.7 联合查询

对于union查询,就是把多次查询的结果合并起来,形成一个新的查询结果

语法:

        select 字段列表 from 表A

        union[ALL]

        select 字段列表 from 表B ...;

-- union all , union
-- 将薪资低于5000的员工 和年龄大于50岁的员工全部查询出来
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; -- 去重合并

 非去重查询结果

 去重查询结果

8.事务

  • 事务简介

        事务是一组操作的集合,它是一个不可分割的工作单位,事务会把所有的操作作为一个整体,一起向系统提交或撤销操作请求,即这些操作要么同时成功,要么同时失败

        默认MySQL的事务是自动提交的,也就是说,当执行一条DML语句,MySQL会立即隐式的提交事务。

  • 事务操作
    • select @@autocommit;   查看是否是自动提交(如果是1则执行代码后自动提交)
    • set @@autocommit = 0;    设置手动提交(进行commit才能提交)
    • begin  或  start transaction  开启事务(之后执行的操作必须提交之后才有用)
    • commit                                 提交事务(提交begin之后进行的操作)
    • rollback                                回滚事务(恢复到begin之前的状态)
  • 事务四大特性
    • 原子性(Atomicity):事务是不可分割的最小操作单元,要么全部成功,要么全部失败
    • 一致性(Consistency):事物完成时,必须使所有的数据都保持一致状态。
    • 隔离性(Isolation):数据库系统提供的隔离机制,保证事务再不受外部的并发操作影响的独立环境下运行。
    • 持久性(Durability):事务一旦提交或回滚,它对数据库中的改变就是永久的。
  • 并发事务问题
    • 问题发生情况:

                脏读

                

                不可重复读:

                

                幻读:

                

  • 事务隔离级别

注:在MySQL中默认隔离级别为Repeatable Read

        而在Oracle中默认隔离级别为Read committed

        -- 查看事务隔离级别

        select @@transaction_isolation

        --设置事务隔离级别

        set [session | global ] transaction isolation level { read uncommitten |

read committed | repeatable read | serializable }

session  设置当前会话隔离级别
 

8.1 事务操作

select @@autocommit;

set @@autocommit = 1; -- 设置手动提交

begin;

select * from accont where name = '张三';

update accont set money = money - 1000 where name = '张三';

update accont set money = money + 1000 where name = '李四';

-- 提交事务
commit;

rollback ;

 8.2 事务隔离级别

注:在MySQL中默认隔离级别为Repeatable Read

        而在Oracle中默认隔离级别为Read committed

        -- 查看事务隔离级别

        select @@transaction_isolation

        --设置事务隔离级别

        set [session | global ] transaction isolation level { read uncommitten |

read committed | repeatable read | serializable }

session  设置当前会话隔离级别

8.2.1 脏读

当隔离级别为read uncommitted时,会发生脏读问题

 当隔离级别改为read committed后,将不再发生脏读

8.2.2 不可重复读

 

在隔离级别为Read committed 时,会发生不可重复读的问题(在事务之中读到的数据不同)

隔离级别为 repeatable read时,不会发生不可重复读的问题(在同一个事务内,数据不会被影响)

 8.2.3 幻读

当隔离级别为repeatable read 时,会发生幻读

但在客户端1事务提交之后,确实能读出来客户端2所插入的id = 3的数据 

而当隔离级别为 serializable,在客户端1执行事务期间,其他客户端运行代码时会被阻塞,因此不会发生幻读,但这种方式效率较低

  • 19
    点赞
  • 22
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值