• mysql数据库


    1.视图

    2.触发器

    3.事务

    4.存储过程

    5.pymysql调用存储过程

    6.函数(内置函数)

    7.流程控制

    一.视图

    1.什么是视图
      视图就是通过查询得到的一张虚拟表,然后保存下来,下次直接使用即可

    2.为什么要使用视图

      当频繁需要用到多张表的连表的结果,你就可以事先生成好视图,
     之后直接调用即可,这样避免了反复写连表操作的sql语句

    3.如何使用

      create view teacher_course as select * from teacher INNER JOIN course
      on teacher.tid = course.teacher_id;

    强调:
      1.视图只有表结构,视图中的数据还是来源于原来的表
      2.不要改动视图表中的数据
      3.一般情况下不会频繁的使用视图来写业务逻辑

    补充:那么在开发中会不会取使用视图     不会

    不会!视图是mysql的功能,如果你的项目里面大量的使用到了视图,那意味着你后期想要扩张某个功能的时候这个功能恰巧又需要对视图进行修改,
    意味着你需要先在mysql这边将视图先修改一下,然后再去应用程序中修改对应的sql语句,这就涉及到跨部门沟通的问题,所以通常不会使用视图,
    而是通过重新修改sql语句来扩展功能

    二.触发器

    1.什么是触发器

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

    2.为什么要使用触发器

      触发器专门针对我们对某一张表数据的insert,删delete,改update的行为,

    这类行为一旦执行就会触发触发器的执行,即自动运行另外一段sql代码

    那么触发器的语法该怎么写:

     1 # 针对插入
     2 create trigger tri_after_insert_t1 after insert on 表名 for each row
     3 begin
     4     sql代码。。。
     5 end 
     6 create trigger tri_after_insert_t2 before insert on 表名 for each row
     7 begin
     8     sql代码。。。
     9 end
    10 
    11 # 针对删除
    12 create trigger tri_after_delete_t1 after delete on 表名 for each row
    13 begin
    14     sql代码。。。
    15 end
    16 create trigger tri_after_delete_t2 before delete on 表名 for each row
    17 begin
    18     sql代码。。。
    19 end
    20 
    21 # 针对修改
    22 create trigger tri_after_update_t1 after update on 表名 for each row
    23 begin
    24     sql代码。。。
    25 end
    26 create trigger tri_after_update_t2 before update on 表名 for each row
    27 begin
    28     sql代码。。。
    29 end
    30 
    31 # 案例
    32 CREATE TABLE cmd (
    33     id INT PRIMARY KEY auto_increment,
    34     USER CHAR (32),
    35     priv CHAR (10),
    36     cmd CHAR (64),
    37     sub_time datetime, #提交时间
    38     success enum ('yes', 'no') #0代表执行失败
    39 );
    40 
    41 CREATE TABLE errlog (
    42     id INT PRIMARY KEY auto_increment,
    43     err_cmd CHAR (64),
    44     err_time datetime
    45 );
    46 
    47 delimiter $$  # 将mysql默认的结束符由;换成$$
    48 create trigger tri_after_insert_cmd after insert on cmd for each row
    49 begin
    50     if NEW.success = 'no' then  # 新记录都会被MySQL封装成NEW对象
    51         insert into errlog(err_cmd,err_time) values(NEW.cmd,NEW.sub_time);
    52     end if;
    53 end $$
    54 delimiter ;  # 结束之后记得再改回来,不然后面结束符就都是$$了
    55 
    56 #往表cmd中插入记录,触发触发器,根据IF的条件决定是否插入错误日志
    57 INSERT INTO cmd (
    58     USER,
    59     priv,
    60     cmd,
    61     sub_time,
    62     success
    63 )
    64 VALUES
    65     ('egon','0755','ls -l /etc',NOW(),'yes'),
    66     ('egon','0755','cat /etc/passwd',NOW(),'no'),
    67     ('egon','0755','useradd xxx',NOW(),'no'),
    68     ('egon','0755','ps aux',NOW(),'yes');
    69 
    70 # 查询errlog表记录
    71 select * from errlog;
    72 # 删除触发器
    73 drop trigger tri_after_insert_cmd;
    View Code

    三.事务

    什么是事务:
    开启一个事务可以包含一些sql语句,这些sql语句要么同时成功,要么一个都别想成功,称之为事务的原子性
    
    
    事务的作用:
    保证了对数据操作的数据安全,
    
    案例:用交行的卡操作建行ATM机给工商的账户转钱、
    
    
    
    事务有4个必须具有的属性:
    1.原子性(atomicity):一个事务是一个不可分割的工作单位,事务中包括的操作要么都做要么都不做
    
    2.一致性(consistency):事务必须是使数据库从一个一致性状态变到另一个一致性状态,一致性与原子性是密切相关的
    
    3.一个事务的执行不能被其他事务干扰。即一个事务内部的操作及使用的数据对并发的其他事务是隔离的,并发执行的各个事务之间不能互相干扰。
    
    4.。持久性也称永久性(permanence),指一个事务一旦提交,它对数据库中数据的改变就应该是永久性的。接下来的其他操作或故障不应该对其有任何影响。

    代码演示如何使用:

     1 create table user(
     2 id int primary key auto_increment,
     3 name char(32),
     4 balance int
     5 );
     6 
     7 insert into user(name,balance)
     8 values
     9 ('wsb',1000),
    10 ('egon',1000),
    11 ('ysb',1000);
    12 
    13 # 修改数据之前先开启事务操作
    14 start transaction;
    15 
    16 # 修改操作
    17 update user set balance=900 where name='wsb'; #买支付100元
    18 update user set balance=1010 where name='egon'; #中介拿走10元
    19 update user set balance=1090 where name='ysb'; #卖家拿到90元
    20 
    21 # 回滚到上一个状态
    22 rollback;
    23 
    24 # 开启事务之后,只要没有执行commit操作,数据其实都没有真正刷新到硬盘
    25 commit;
    26 """开启事务检测操作是否完整,不完整主动回滚到上一个状态,如果完整就应该执行commit操作"""
    27 
    28 # 站在python代码的角度,应该实现的伪代码逻辑,
    29 try:
    30     update user set balance=900 where name='wsb'; #买支付100元
    31     update user set balance=1010 where name='egon'; #中介拿走10元
    32     update user set balance=1090 where name='ysb'; #卖家拿到90元
    33 except 异常:
    34     rollback;
    35 else:
    36     commit;
    37 
    38 # 那如何检测异常?
    View Code

    四.存储过程

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

    有三种开发模型:

    第一种:
    """
    应用程序:只需要开发应用程序的逻辑
    mysql:编写好存储过程,以供应用程序调用
    优点:开发效率,执行效率都高
    缺点:考虑到人为因素、跨部门沟通等问题,会导致扩展性差
    """
    
    第二种:
    """
    应用程序:除了开发应用程序的逻辑,还需要编写原生sql
    优点:比方式1,扩展性高(非技术性的)
    缺点:
    1、开发效率,执行效率都不如方式1
    2、编写原生sql太过于复杂,而且需要考虑到sql语句的优化问题
    """
    
    第三种:
    """
    应用程序:开发应用程序的逻辑,不需要编写原生sql,基于别人编写好的框架来处理数据,ORM
    优点:不用再编写纯生sql,这意味着开发效率比方式2高,同时兼容方式2扩展性高的好处
    缺点:执行效率连方式2都比不过
    """

    如何创建存储过程:

     1 delimiter $$
     2 create procedure p1(
     3     in m int,  # in表示这个参数必须只能是传入不能被返回出去
     4     in n int,  
     5     out res int  # out表示这个参数可以被返回出去,还有一个inout表示即可以传入也可以被返回出去
     6 )
     7 begin
     8     select tname from teacher where tid > m and tid < n;
     9     set res=0;
    10 end $$
    11 delimiter ;
    View Code

    如何使用存储过程:

     1 # 大前提:存储过程在哪个库下面创建的只能在对应的库下面才能使用!!!
     2 
     3 # 1、直接在mysql中调用
     4 set @res=10  # res的值是用来判断存储过程是否被执行成功的依据,所以需要先定义一个变量@res存储10
     5 call p1(2,4,10);  # 报错
     6 call p1(2,4,@res);  
     7 
     8 # 查看结果
     9 select @res;  # 执行成功,@res变量值发生了变化
    10 
    11 # 2、在python程序中调用
    12 pymysql链接mysql
    13 产生的游表cursor.callproc('p1',(2,4,10))  # 内部原理:@_p1_0=2,@_p1_1=4,@_p1_2=10;
    14 cursor.excute('select @_p1_2;')
    15 
    16 
    17 # 3、存储过程与事务使用举例(了解)
    18 delimiter //
    19 create PROCEDURE p5(
    20     OUT p_return_code tinyint
    21 )
    22 BEGIN
    23     DECLARE exit handler for sqlexception
    24     BEGIN
    25         -- ERROR
    26         set p_return_code = 1;
    27         rollback;
    28     END;
    29 
    30 
    31   DECLARE exit handler for sqlwarning
    32   BEGIN
    33       -- WARNING
    34       set p_return_code = 2;
    35       rollback;
    36   END;
    37 
    38   START TRANSACTION;
    39       update user set balance=900 where id =1;
    40       update user123 set balance=1010 where id = 2;
    41       update user set balance=1090 where id =3;
    42   COMMIT;
    43 
    44   -- SUCCESS
    45   set p_return_code = 0; #0代表执行成功
    46 
    47 
    48 END //
    49 delimiter ;
    View Code

    五.函数

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

    参考博客:http://www.cnblogs.com/linhaifeng/articles/7495918.html#_label2

     1 CREATE TABLE blog (
     2     id INT PRIMARY KEY auto_increment,
     3     NAME CHAR (32),
     4     sub_time datetime
     5 );
     6 
     7 INSERT INTO blog (NAME, sub_time)
     8 VALUES
     9     ('第1篇','2015-03-01 11:31:21'),
    10     ('第2篇','2015-03-11 16:31:21'),
    11     ('第3篇','2016-07-01 10:21:31'),
    12     ('第4篇','2016-07-22 09:23:21'),
    13     ('第5篇','2016-07-23 10:11:11'),
    14     ('第6篇','2016-07-25 11:21:31'),
    15     ('第7篇','2017-03-01 15:33:21'),
    16     ('第8篇','2017-03-01 17:32:21'),
    17     ('第9篇','2017-03-01 18:31:21');
    18 
    19 select date_format(sub_time,'%Y-%m'),count(id) from blog group by date_format(sub_time,'%Y-%m');
    View Code

    六.流程控制

    if 条件语句

     1 # if条件语句
     2 delimiter //
     3 CREATE PROCEDURE proc_if ()
     4 BEGIN
     5     
     6     declare i int default 0;
     7     if i = 1 THEN
     8         SELECT 1;
     9     ELSEIF i = 2 THEN
    10         SELECT 2;
    11     ELSE
    12         SELECT 7;
    13     END IF;
    14 
    15 END //
    16 delimiter ;
    View Code

    while循环

     1 # while循环
     2 delimiter //
     3 CREATE PROCEDURE proc_while ()
     4 BEGIN
     5 
     6     DECLARE num INT ;
     7     SET num = 0 ;
     8     WHILE num < 10 DO
     9         SELECT
    10             num ;
    11         SET num = num + 1 ;
    12     END WHILE ;
    13 
    14 END //
    15 delimiter ;
    View Code

    七.索引与慢查询优化

     1 知识回顾:数据都是存在硬盘上的,那查询数据不可避免的需要进行IO操作
     2 
     3 *索引在MySQL中也叫做“键”,是存储引擎用于快速找到记录的一种数据结构。*
     4 
     5 - primary key
     6 - unique key
     7 - index key
     8 
     9 注意foreign key不是用来加速查询用的,不在我们研究范围之内,上面三种key前两种除了有加速查询的效果之外还有额外的约束条件(primary key:非空且唯一,unique key:唯一),而index key没有任何约束功能只会帮你加速查询
    10 
    11 索引就是一种数据结构,类似于书的目录。意味着以后再查数据应该先找目录再找数据,而不是用翻页的方式查询数据
    12 
    13 **本质都是:通过不断地缩小想要获取数据的范围来筛选出最终想要的结果,同时把随机的事件变成顺序的事件,也就是说,有了这种索引机制,我们可以总是用同一种查找方式来锁定数据。**
    14 
    15 **索引的影响:**
    16 
    17 - 在表中有大量数据的前提下,创建索引速度会很慢
    18 - 在索引创建完毕后,对表的查询性能会大幅度提升,但是写的性能会降低
    19 
    20 #### b+树
    21 
    22 <https://images2017.cnblogs.com/blog/1036857/201709/1036857-20170912011123500-158121126.png>
    23 
    24 只有叶子结点存放真实数据,根和树枝节点存的仅仅是虚拟数据
    25 
    26 查询次数由树的层级决定,层级越低次数越少
    27 
    28 一个磁盘块儿的大小是一定的,那也就意味着能存的数据量是一定的。如何保证树的层级最低呢?一个磁盘块儿存放占用空间比较小的数据项
    29 
    30 思考我们应该给我们一张表里面的什么字段字段建立索引能够降低树的层级高度>>> 主键id字段
    31 
    32 #### **聚集索引(primary key)**
    33 
    34 聚集索引其实指的就是表的主键,innodb引擎规定一张表中必须要有主键。先来回顾一下存储引擎。
    35 
    36 myisam在建表的时候对应到硬盘有几个文件(三个)?
    37 
    38 innodb在建表的时候对应到硬盘有几个文件(两个)?frm文件只存放表结构,不可能放索引,也就意味着innodb的索引跟数据都放在idb表数据文件中。
    39 
    40 **特点:**叶子结点放的一条条完整的记录
    41 
    42 #### 辅助索引(unique,index)
    43 
    44 辅助索引:查询数据的时候不可能都是用id作为筛选条件,也可能会用name,password等字段信息,那么这个时候就无法利用到聚集索引的加速查询效果。就需要给其他字段建立索引,这些索引就叫辅助索引
    45 
    46 **特点:**叶子结点存放的是辅助索引字段对应的那条记录的主键的值(比如:按照name字段创建索引,那么叶子节点存放的是:{name对应的值:name所在的那条记录的主键值})
    47 
    48 select name from user where name='jason';
    49 
    50 上述语句叫覆盖索引:只在辅助索引的叶子节点中就已经找到了所有我们想要的数据
    51 
    52 select age from user where name='jason';
    53 
    54 上述语句叫非覆盖索引,虽然查询的时候命中了索引字段name,但是要查的是age字段,所以还需要利用主键才去查找
    View Code

    测试索引(所要准备的表)

      1 ```mysql
      2 #1. 准备表
      3 create table s1(
      4 id int,
      5 name varchar(20),
      6 gender char(6),
      7 email varchar(50)
      8 );
      9 
     10 #2. 创建存储过程,实现批量插入记录
     11 delimiter $$ #声明存储过程的结束符号为$$
     12 create procedure auto_insert1()
     13 BEGIN
     14     declare i int default 1;
     15     while(i<3000000)do
     16         insert into s1 values(i,'jason','male',concat('jason',i,'@oldboy'));
     17         set i=i+1;
     18     end while;
     19 END$$ #$$结束
     20 delimiter ; #重新声明 分号为结束符号
     21 
     22 #3. 查看存储过程
     23 show create procedure auto_insert1G 
     24 
     25 #4. 调用存储过程
     26 call auto_insert1();
     27 ```
     28 
     29 ```mysql 
     30 # 表没有任何索引的情况下
     31 select * from s1 where id=30000;
     32 # 避免打印带来的时间损耗
     33 select count(id) from s1 where id = 30000;
     34 select count(id) from s1 where id = 1;
     35 
     36 # 给id做一个主键
     37 alter table s1 add primary key(id);  # 速度很慢
     38 
     39 select count(id) from s1 where id = 1;  # 速度相较于未建索引之前两者差着数量级
     40 select count(id) from s1 where name = 'jason'  # 速度仍然很慢
     41 
     42 
     43 """
     44 范围问题
     45 """
     46 # 并不是加了索引,以后查询的时候按照这个字段速度就一定快   
     47 select count(id) from s1 where id > 1;  # 速度相较于id = 1慢了很多
     48 select count(id) from s1 where id >1 and id < 3;
     49 select count(id) from s1 where id > 1 and id < 10000;
     50 select count(id) from s1 where id != 3;
     51 
     52 alter table s1 drop primary key;  # 删除主键 单独再来研究name字段
     53 select count(id) from s1 where name = 'jason';  # 又慢了
     54 
     55 create index idx_name on s1(name);  # 给s1表的name字段创建索引
     56 select count(id) from s1 where name = 'jason'  # 仍然很慢!!!
     57 """
     58 再来看b+树的原理,数据需要区分度比较高,而我们这张表全是jason,根本无法区分
     59 那这个树其实就建成了“一根棍子”
     60 """
     61 select count(id) from s1 where name = 'xxx';  
     62 # 这个会很快,我就是一根棍,第一个不匹配直接不需要再往下走了
     63 select count(id) from s1 where name like 'xxx';
     64 select count(id) from s1 where name like 'xxx%';
     65 select count(id) from s1 where name like '%xxx';  # 慢 最左匹配特性
     66 
     67 # 区分度低的字段不能建索引
     68 drop index idx_name on s1;
     69 
     70 # 给id字段建普通的索引
     71 create index idx_id on s1(id);
     72 select count(id) from s1 where id = 3;  # 快了
     73 select count(id) from s1 where id*12 = 3;  # 慢了  索引的字段一定不要参与计算
     74 
     75 drop index idx_id on s1;
     76 select count(id) from s1 where name='jason' and gender = 'male' and id = 3 and email = 'xxx';
     77 # 针对上面这种连续多个and的操作,mysql会从左到右先找区分度比较高的索引字段,先将整体范围降下来再去比较其他条件
     78 create index idx_name on s1(name);
     79 select count(id) from s1 where name='jason' and gender = 'male' and id = 3 and email = 'xxx';  # 并没有加速
     80 
     81 drop index idx_name on s1;
     82 # 给name,gender这种区分度不高的字段加上索引并不难加快查询速度
     83 
     84 create index idx_id on s1(id);
     85 select count(id) from s1 where name='jason' and gender = 'male' and id = 3 and email = 'xxx';  # 快了  先通过id已经讲数据快速锁定成了一条了
     86 select count(id) from s1 where name='jason' and gender = 'male' and id > 3 and email = 'xxx';  # 慢了  基于id查出来的数据仍然很多,然后还要去比较其他字段
     87 
     88 drop index idx_id on s1
     89 
     90 create index idx_email on s1(email);
     91 select count(id) from s1 where name='jason' and gender = 'male' and id > 3 and email = 'xxx';  # 快 通过email字段一剑封喉 
     92 ```
     93 
     94 #### 联合索引
     95 
     96 ```mysql
     97 select count(id) from s1 where name='jason' and gender = 'male' and id > 3 and email = 'xxx';  
     98 # 如果上述四个字段区分度都很高,那给谁建都能加速查询
     99 # 给email加然而不用email字段
    100 select count(id) from s1 where name='jason' and gender = 'male' and id > 3; 
    101 # 给name加然而不用name字段
    102 select count(id) from s1 where gender = 'male' and id > 3; 
    103 # 给gender加然而不用gender字段
    104 select count(id) from s1 where id > 3; 
    105 
    106 # 带来的问题是所有的字段都建了索引然而都没有用到,还需要花费四次建立的时间
    107 create index idx_all on s1(email,name,gender,id);  # 最左匹配原则,区分度高的往左放
    108 select count(id) from s1 where name='jason' and gender = 'male' and id > 3 and email = 'xxx';  # 速度变快
    109 ```
    View Code
  • 相关阅读:
    servlet里的forward和redirect的区别
    JSP九大内置对象
    float和Float的区别
    Throwable相关知识1
    常见异常和错误总结
    final/finalize/finally的区别
    mysql命令大全
    mongodb安装
    mysql编译安装(详细)
    mysql的三种安装方式(详细)
  • 原文地址:https://www.cnblogs.com/zahngyu/p/11400581.html
Copyright © 2020-2023  润新知