数据库6

  • 视图
  • 触发器
  • 事务
  • 存储过程
  • 内置函数
  • 流程控制
  • 索引

视图

视图就是通过查询得到一张虚拟表,保存下来方便下次使用。

为什么要使用视图

若要重复使用一张虚拟表,可以不用重复查询(节省拼接表的时间消耗)

如何使用视图

# create view 视图名 as sql语句
create view teacher2course as
select * from teacher inner join course on teacher.tid = course.teacher_id;
  • 在硬盘中,视图只有表结构文件,没有表数据文件
  • 视图通常是用来查询,不要修改视图中的数据
删除视图
drop view teacher2course;

触发器

在满足对某张表数据的增、删、改的条件下,自动触发的功能称为触发器

为何使用触发器

为了在对某张表数据进行insert、delete、update的行为时,自动运行另一段sql代码

创建触发器语法

# 完整语法
create trigger 触发器名字 before/after insert/update/delete on 表名 for each row
begin
    sql代码...
end
# 触发器命名规律
tri_before_insert_t1

# 针对插入
create trigger tri_before_insert_t1 before insert on t1 for each row
begin
    sql...
end

create trigger tri_after_insert_t1 after insert on t1 for each row
begin
    sql...
end
# 针对删除
create trigger tri_before_delete_t1 before delete on t1 for each row
begin
    sql...
end

create trigger tri_after_delete_t1 after delete on t1 for each row
begin
    sql...
end
# 针对修改
create trigger tri_before_update_t1 before update on t1 for each row
begin
    sql...
end

create trigger tri_after_update_t1 after update on t1 for each row
begin
    sql...
end

# 案例
create table cmd(
    id int primary key auto_increment,
    user char(32),
    priv char(10),
    cmd char(64),
    sub_time datetime, # 提交时间
    success enum('yes', 'no') # 0代表执行失败
);

create table errlog(
    id int primary key auto_increment,
    err_cmd char(64),
    err_time datetime
);

'''
知识点补充:
    sql语句默认是以分号结束,可以使用delimiter临时修改结束符,只在当前库有效,若当前窗口关闭也会失效
'''

delimiter ¥  # 讲mysql默认结束符由;换成¥
create trigger tri_after_insert_cmd after insert on cmd for each row
begin
    if new.success = 'no' then # 新记录都会被mysql封装成new对象
        insert into errlog(err_cmd,err_time) values(new.cmd,new.sub_time);
    end if; # 若不修改结束符,在这一步代码就会提交
end ¥
delimiter ; # 结束之后记得将结束符修改回来

# 往表中插入记录,触发触发器,根据if条件决定是否插入错误日志
insert into cmd(
    user,
    priv,
    cmd,
    sub_time,
    success
)
values 
    ('lll','1024','ls -l /etc',NOW(),'yes'),
    ('lll','1024','cat /etc/passwd',NOW(),'no'),
    ('lll','1024','useradd xxx',NOW(),'no'),
    ('lll','1024','ps aux',NOW(),'yes');
    
# 查询errlog表记录
select * from errlog;
# 删除触发器
drop trigger tri_after_insert_cmd;

事务

事务用于将某些操作的多个sql作为原子性操作,一旦有某一个出现错误,即可回滚到原来的状态,从而保证数据库数据完整性

(开启一个事务包含一些sql语句,这些sql语句要么同时成功,要么都别成功)

事务的作用

保证了对数据操作的数据安全性,一致性

事务的四大特性:ACID特性

原子性:一个事务时一个不可分割的工作单位,事务中包括的操作要么都做,要么都不做。

一致性:事务必须是使数据库从一个一致性状态变到另一个一致性状态。一致性与原子性是密切相关的

隔离性:一个事务的执行不能被其他事务干扰,即一个事务内部的操作及使用的数据对并发的其他事务是隔离的,并发执行的各事务之间不能互相干扰

持久性:持久性也称永久性,指一个事务一旦提交,它对数据库中数据的改变就应该是永久性的,接下来的其他操作或故障不应该对其有任何影响。

如何使用

开启事务:start transaction;

回滚:rollback

确认:commit

create table user(
    id int primary key auto_increment,
    name char(32),
    balance int
);

insert into user(name,balance)
values
('lll',1000),
('zzz',1000),
('nnn',1000);

# 修改数据之前先开启事务操作
start transaction;

# 修改操作
update user set balance=900 where name='lll'; # 买家支付100
update user set balance=1010 where name='zzz'; # 中介拿走10
update user set balance=1090 where name='nnn'; # 卖家拿到90

# 回滚到上一个状态
rollback;

# 开启事务之后,只要没有执行commit操作,数据其实都没有真正刷新到硬盘
commit;
'''
开启事务检测操作是否完整,不完整主动回滚到上一个状态,如果完整就应该执行commit操作
'''

存储过程

(自定义函数)

存储过程包含了一系列可执行的sql语句,存储过程存放于mysql中,通过调用它的名字可以执行其内部的一堆sql

关键字:procedure

创建存储过程

# 语法结构
create procedure 存储过程的名字(
    形参1,
    形参2,
    形参3,
)
begin
    sql语句;
end


# 无参
delimiter $$
create procedure p1()
begin
    select * from user;
end
delimiter

call p1(); # mysql中调用


# 有参
delimiter $$
create procedure p1(
    in m int, # in表示这个参数必须只能是传入不能被返回出去
    in n int,
    out res int # out表示这个参数可以被返回出去,还有一个inout表示即可以传入也可以被返回出去
)
begin 
    select tname from teacher where tid > m and tid < n;
    set res=0; # 设置(修改)形参的值
end $$
delimiter ;
# 返回值 用来判断当前存储过程是否执行成功

如何用存储过程

# 大前提:存储过程在哪个库下面创建的只能在对应的库下面才能使用
# 1、直接在mysql中调用
set @res=10 # res的值用来判断存储过程是否被执行成功的依据,所以需要先定义一个变量存储10
call p1(2,4,10); # 报错
call p1(2,4,@res);

# 查看结果
select @res; # 执行成功,@res变量值发生变化

# 2、在python程序中调用
pymysql连接mysql
产生的游标cursor.callproc('p1',(2,4,10)) 
'''
内部原理:@_存储过程的名字_索引 = 值
        @_p1_0=1,@_p1_1=6,@_p1_2=10  内部自动用变量存储
'''
cursor.execute('select @_p1_2;')

# 3、存储过程与事务使用举例(了解。。。)
delimiter //
create PROCEDURE p5(
    OUT p_return_code tinyint
)
BEGIN
    DECLARE exit handler for sqlexception
    BEGIN
        -- ERROR
        set p_return_code = 1;
        rollback;
    END;


  DECLARE exit handler for sqlwarning
  BEGIN
      -- WARNING
      set p_return_code = 2;
      rollback;
  END;

  START TRANSACTION;
      update user set balance=900 where id =1;
      update user123 set balance=1010 where id = 2;
      update user set balance=1090 where id =3;
  COMMIT;

  -- SUCCESS
  set p_return_code = 0; #0代表执行成功


END //
delimiter ;

函数

(内置函数)

与存储过程的区别,mysql内置的函数只能在sql语句中使用

create table blog(
    id int primary key auto_increment,
    name char(32),
    sub_time datetime
);

insert into blog (name, sub_time)
values
('yyh闯荡红灯区实录1','2017-01-01 00:00:00'),
('yyh闯荡红灯区实录2','2017-01-02 12:07:30'),
('yyh闯荡红灯区实录3','2018-03-03 16:21:25'),
('yyh闯荡红灯区实录4','2019-07-04 18:32:43'),
('yyh闯荡红灯区实录5','2019-07-05 21:00:05');

select date_format(sub_time,'%Y-%m'),count(id) from blog group by
date_format(sub_time,'%Y-%m');

流程控制

# if条件语句
delimiter //
create procedure pro_if()
begin
    declare i int default 0;
    if i = 1 then
        select 1;
    elseif i = 2 then
        select 2;
    else
        select 7;
    end if;

end //
delimiter ;
# while循环
delimiter //
create procedure proc_while()
begin
    declare num int;
    set num = 0;
    while num <10 do
        select
            num;
        set num = num + 1;
    
    end while;
end //
delimiter ;

索引与慢查询优化

索引:加快数据查询,索引就类似于书的目录

索引虽然能加速查询 但是在插入或者修改数据的时候 索引反而会降低速度
(销毁与创建)

索引在MySQL中也叫做“键”,是存储引擎用于快速找到记录的一种数据结构。

  • primary key
  • unique key
  • index key

注意foreign key不是用来加速查询用的,不在我们研究范围之内,上面三种key前两种除了有加速查询的效果之外还有额外的约束条件(primary key:非空且唯一,unique key:唯一),而index key没有任何约束功能只会帮你加速查询

索引就是一种数据结构,类似于书的目录。意味着以后再查数据应该先找目录再找数据,而不是用翻页的方式查询数据

本质都是:通过不断地缩小想要获取数据的范围来筛选出最终想要的结果,同时把随机的事件变成顺序的事件,也就是说,有了这种索引机制,我们可以总是用同一种查找方式来锁定数据。

索引的影响:

  • 在表中有大量数据的前提下,创建索引速度会很慢
  • 在索引创建完毕后,对表的查询性能会大幅度提升,但是写的性能会降低

b+树

只有叶子结点存放真实数据,根和树枝节点存的仅仅是虚拟数据

查询次数由树的层级决定,层级越低次数越少

一个磁盘块儿的大小是一定的,那也就意味着能存的数据量是一定的。如何保证树的层级最低呢?一个磁盘块儿存放占用空间比较小的数据项

思考我们应该给我们一张表里面的什么字段字段建立索引能够降低树的层级高度>>> 主键id字段

聚集索引(primary key)

聚集索引其实指的就是表的主键,innodb引擎规定一张表中必须要有主键。先来回顾一下存储引擎。

myisam在建表的时候对应到硬盘有几个文件(三个)?

innodb在建表的时候对应到硬盘有几个文件(两个)?frm文件只存放表结构,不可能放索引,也就意味着innodb的索引跟数据都放在idb表数据文件中。

特点:叶子结点放的一条条完整的记录

辅助索引(unique,index)

辅助索引:查询数据的时候不可能都是用id作为筛选条件,也可能会用name,password等字段信息,那么这个时候就无法利用到聚集索引的加速查询效果。就需要给其他字段建立索引,这些索引就叫辅助索引

特点:叶子结点存放的是辅助索引字段对应的那条记录的主键的值(比如:按照name字段创建索引,那么叶子节点存放的是:{name对应的值:name所在的那条记录的主键值})

select name from user where name='jason';

上述语句叫覆盖索引:只在辅助索引的叶子节点中就已经找到了所有我们想要的数据

select age from user where name='jason';

上述语句叫非覆盖索引,虽然查询的时候命中了索引字段name,但是要查的是age字段,所以还需要利用主键才去查找

测试索引

准备

#1. 准备表
create table s1(
id int,
name varchar(20),
gender char(6),
email varchar(50)
);

#2. 创建存储过程,实现批量插入记录
delimiter $$ #声明存储过程的结束符号为$$
create procedure auto_insert1()
BEGIN
    declare i int default 1;
    while(i<3000000)do
        insert into s1 values(i,'jason','male',concat('jason',i,'@oldboy'));
        set i=i+1;
    end while;
END$$ #$$结束
delimiter ; #重新声明分号为结束符号

#3. 查看存储过程
show create procedure auto_insert1\G 

#4. 调用存储过程
call auto_insert1();
# 表没有任何索引的情况下
select * from s1 where id=30000;
# 避免打印带来的时间损耗
select count(id) from s1 where id = 30000;
select count(id) from s1 where id = 1;

# 给id做一个主键
alter table s1 add primary key(id);  # 速度很慢

select count(id) from s1 where id = 1;  # 速度相较于未建索引之前两者差着数量级
select count(id) from s1 where name = 'jason'  # 速度仍然很慢


"""
范围问题
"""
# 并不是加了索引,以后查询的时候按照这个字段速度就一定快   
select count(id) from s1 where id > 1;  # 速度相较于id = 1慢了很多
select count(id) from s1 where id >1 and id < 3;
select count(id) from s1 where id > 1 and id < 10000;
select count(id) from s1 where id != 3;

alter table s1 drop primary key;  # 删除主键 单独再来研究name字段
select count(id) from s1 where name = 'jason';  # 又慢了

create index idx_name on s1(name);  # 给s1表的name字段创建索引
select count(id) from s1 where name = 'jason'  # 仍然很慢!!!
"""
再来看b+树的原理,数据需要区分度比较高,而我们这张表全是jason,根本无法区分
那这个树其实就建成了“一根棍子”
"""
select count(id) from s1 where name = 'xxx';  
# 这个会很快,我就是一根棍,第一个不匹配直接不需要再往下走了
select count(id) from s1 where name like 'xxx';
select count(id) from s1 where name like 'xxx%';
select count(id) from s1 where name like '%xxx';  # 慢 最左匹配特性

# 区分度低的字段不能建索引
drop index idx_name on s1;

# 给id字段建普通的索引
create index idx_id on s1(id);
select count(id) from s1 where id = 3;  # 快了
select count(id) from s1 where id*12 = 3;  # 慢了  索引的字段一定不要参与计算

drop index idx_id on s1;
select count(id) from s1 where name='jason' and gender = 'male' and id = 3 and email = 'xxx';
# 针对上面这种连续多个and的操作,mysql会从左到右先找区分度比较高的索引字段,先将整体范围降下来再去比较其他条件
create index idx_name on s1(name);
select count(id) from s1 where name='jason' and gender = 'male' and id = 3 and email = 'xxx';  # 并没有加速

drop index idx_name on s1;
# 给name,gender这种区分度不高的字段加上索引并不难加快查询速度

create index idx_id on s1(id);
select count(id) from s1 where name='jason' and gender = 'male' and id = 3 and email = 'xxx';  # 快了  先通过id已经讲数据快速锁定成了一条了
select count(id) from s1 where name='jason' and gender = 'male' and id > 3 and email = 'xxx';  # 慢了  基于id查出来的数据仍然很多,然后还要去比较其他字段

drop index idx_id on s1

create index idx_email on s1(email);
select count(id) from s1 where name='jason' and gender = 'male' and id > 3 and email = 'xxx';  # 快 通过email字段一剑封喉 

联合索引

select count(id) from s1 where name='jason' and gender = 'male' and id > 3 and email = 'xxx';  
# 如果上述四个字段区分度都很高,那给谁建都能加速查询
# 给email加然而不用email字段
select count(id) from s1 where name='jason' and gender = 'male' and id > 3; 
# 给name加然而不用name字段
select count(id) from s1 where gender = 'male' and id > 3; 
# 给gender加然而不用gender字段
select count(id) from s1 where id > 3; 

# 带来的问题是所有的字段都建了索引然而都没有用到,还需要花费四次建立的时间
create index idx_all on s1(email,name,gender,id);  # 最左匹配原则,区分度高的往左放
select count(id) from s1 where name='jason' and gender = 'male' and id > 3 and email = 'xxx';  # 速度变快

猜你喜欢

转载自www.cnblogs.com/littleb/p/12056359.html