mysql索引,视图,触发器,存储过程

一. 索引

1.1 索引概念

MySQL官方对索引的定义为:索引(index)是帮助MySQL高效获取数据的数据结构(有序)。在数据之外,数据
库系统还维护者满足特定查找算法的数据结构,这些数据结构以某种方式引用(指向)数据, 这样就可以在这些数
据结构上实现高级查找算法,这种数据结构就是索引。如下面的示意图所示
在这里插入图片描述
左边是数据表,一共有两列七条记录,最左边的是数据记录的物理地址(注意逻辑上相邻的记录在磁盘上也并不是
一定物理相邻的)。为了加快Col2的查找,可以维护一个右边所示的二叉查找树,每个节点分别包含索引键值和一
个指向对应数据记录物理地址的指针,这样就可以运用二叉查找快速获取到相应数据。
一般来说索引本身也很大,不可能全部存储在内存中,因此索引往往以索引文件的形式存储在磁盘上。索引是数据
库中用来提高性能的最常用的工具

1.2 索引的优劣势

优势
提高数据检索的效率,降低数据库的IO成本(输入输出)
通过索引列对数据进行排序,降低数据排序的成本,降低CPU的消耗。

劣势
索引列是需要占用空间的,也就是说索引是一张表,表中保存了主键与索引字段
虽然索引检索效率快,但是增加了数据更新的成本(对表进行INSERT、UPDATE、DELETE),
因为更新表时,MySQL 不仅要保存数据,还要保存一下索引文件每次更新添加了索引列的字段,都会调整因为更新所
带来的键值变化后的索引信息。

重点: 如果想设计索引,必须知道其优劣势 如果不知道其优劣势的话创建索引,不但会引起IO成本的增加,更可能会造成数据库设计崩盘,数据操作反而变慢.

1.3 索引类型

索引是在MySQL的存储引擎层中实现的,而不是在服务器层实现的。所以每种存储引擎的索引都不一定完全相同,
也不是所有的存储引擎都支持所有的索引类型的。MySQL目前提供了以下4种索引:

  • BTREE 索引 : 最常见的索引类型,大部分索引都支持 B 树索引。
  • HASH 索引:只有Memory引擎支持 , 使用场景简单 。
  • R-tree 索引(空间索引):空间索引是MyISAM引擎的一个特殊索引类型,主要用于地理空间数据类型,通常使用较少,不做特别介绍。
  • Full-text (全文索引) :全文索引也是MyISAM的一个特殊索引类型,主要用于全文索引,InnoDB从
  • Mysql5.6版本开始支持全文索引。
    在这里插入图片描述

1.4 索引分类

1) 单值索引 :即一个索引只包含单个列,一个表可以有多个单列索引
2) 唯一索引 :索引列的值必须唯一,但允许有空值
3) 复合索引 :即一个索引包含多个列
4) 主键索引 :即表中主键列

1.5 索引语法

索引在创建表的时候,可以同时创建, 也可以随时增加新的索引。

  1. 查看索引
show index from 表名;
  1. 创建索引
语法: create [unique,fulltext,spatial] index 索引名称 [using 索引类型] on 表名(字段名);
示例: create unique index unique_name using btree on student(name);
  1. 删除索引
语法: drop index 索引名称 on 表名;
示例: drop index unique_name on student;

1.6 索引设计原则

索引的设计可以遵循一些已有的原则,创建索引的时候请尽量考虑符合这些原则,便于提升索引的使用效率,更高效的使用索引

  • 对查询频次较高,且数据量比较大的表建立索引
  • 使用唯一索引,区分度越高,使用索引的效率越高
  • 尽量不要在频繁插入,更新,删除的表建立太多索引. 它会引入相当高的维护代价,降低DML操作的效率,增加相应操作的时间消耗
  • 索引可以有效的提升查询数据的效率,但索引数量不是多多益善,索引越多,维护索引的代价自然也就水涨船高。
  • 索引字段的选择,最佳候选列应当从where子句的条件中提取,如果where子句中的组合比较多,那么应当挑选最常用、过滤效果最好的列的组合
    也可以使用组合索引来提高查询效率

二. 视图

视图(View)是一种虚拟存在的表。视图并不在数据库中实际存在,行和列数据来自定义视图的查询中使用的表,
并且是在使用视图时动态生成的。通俗的讲,视图就是一条SELECT语句执行后返回的结果集。所以我们在创建视
图的时候,主要的工作就落在创建这条SQL查询语句上。

视图相对于普通的表的优势主要包括以下几项。
简单:使用视图的用户完全不需要关心后面对应的表的结构、关联条件和筛选条件,对用户来说已经是过滤好的复合条件的结果集。
安全:使用视图的用户只能访问他们被允许查询的结果集,对表的权限管理并不能限制到某个行某个列,但是通过视图就可以简单的实现。
数据独立:一旦视图的结构确定了,可以屏蔽表结构变化对用户的影响,源表增加列对视图没有影响;源表修改列名,则可以通过修改视图来解决,不会造成对访问者的影响。

创建视图

create [ or replace ] view 视图名称 as 查询语句;

例: create view view_test as select * from student where id = '4';

查看视图

show tables;
desc 视图名称;

查看视图定义

show create view 视图名称;

修改视图

alter view 视图名称 as 查询语句;

alter view view_test as select * from student;

删除视图

drop view 视图名称;

三. 触发器

触发器是与表有关的数据库对象,指在 insert/update/delete 之前或之后,触发并执行触发器中定义的SQL语句集
合。触发器的这种特性可以协助应用在数据库端确保数据的完整性 , 日志记录 , 数据校验等操作 。
使用别名 OLD 和 NEW 来引用触发器中发生变化的记录内容,这与其他的数据库是相似的。现在触发器还只支持
行级触发,不支持语句级触发。

创建触发器语法:

delimiter $

create trigger 触发器名称
before/after  insert/update/delete
on 表名

[ for each row]  -- 行级触发器

begin
    触发器逻辑
end$

delimiter ;

示例 记录日志
数据准备

create table log (
id int(11) not null auto_increment,
operation varchar(20) not null comment '操作类型, insert/update/delete',
operate_time datetime not null comment '操作时间',
operate_id int(11) not null comment '操作表的ID',
operate_params varchar(500) comment '操作参数',
primary key(`id`)
)engine=innodb default charset=utf8;

创建触发器
新增

delimiter $

create trigger student_insert_trigger

after insert

on student

for each row

begin

	insert into log values (null,'insert',now(),new.id,concat('(插入的参数是:id:',new.id,',name:',new.name));

end $

delimiter ;

修改

delimiter $

create trigger student_update_trigger

after update

on student

for each row

begin

	insert into log values (null,'update',now(),old.id,concat('修改前的name:',old.name,',修改后的name:',new.name));

end $

delimiter ;

删除

delimiter $

create trigger student_delete_trigger

after delete

on student

for each row

begin

	insert into log values (null,'delete',now(),old.id,concat('删除前的id:',old.id));

end $

delimiter ;

删除触发器

drop trigger 触发器名称;

查看触发器

show triggers;

四、存储过程

定义变量

在存储过程中 , declare 关键字定义局部变量,其作用域只能在begin…end中

create procedure 存储过程名称()
begin
declare 变量名 变量类型 [default 值];
end

变量赋值

两种方式:

  1. set关键字
 create procedure 存储过程名称()
 begin
     declare 变量名 变量类型;    
     SET 变量名 =  值;
 end
  1. select … into …
create procedure 存储过程名称()
begin 
    declare 变量名 变量类型;
    select 查询字段 into 变量名 from 表名;
end

存储过程 – 条件判断 / 传参

条件判断 if else

create procedure 存储过程名称()
begin
    if 条件表达式 then 逻辑1;
    elseif 条件表达式 then 逻辑2;
    else 逻辑3;
    end if;
end 

示例:

create procedure test05()
begin
    declare height int default 175;
    declare desci varchar(30);
    if height > 175 then 
        set desci = "高挑身材";
    elseif height >= 170 and <= 175  then
        set desci = "标准身材";
   else 
        set desci = "可爱身材";
   end if;
end

传递参数 [重中之重]

in : 该参数可以作为输入参数,也就是需要调用方传入的值 默认项
out : 该参数可以作为输出参数,也就是可以作为返回值给调用方
inout: 该参数可以作为输入,也可以作为输出

create procedure 存储过程名称(int 参数名,out 参数名 参数类型[(参数长度)],inout 参数名 参数类型)
begin

end

create procedure test06(in height int)
begin

    declare desci varchar(30);

    if height >= 180 then
        set desci = "大";
    elseif height >= 170 and height < 180 then
        set desci = "中";
   else 
       set desci = "小";
   end if;

    select desci;

end

示例:

create procedure test07(in height int ,out desci varchar(30))

begin
    if height >= 180 then set desci = "大";
    elseif height < 180 and height >= 170 then set desci = "中";
    else set desci = "小";
    end if;
end

调用 out

call(168,@desci);

输出 out

select @desci;

@desci : 这种变量要在变量名称前面加上“@”符号,叫做用户会话变量,代表整个会话过程他都是有作用的,这个类似于全局变量一样。
@@global.sort_buffffer_size : 这种在变量前加上 “@@” 符号, 叫做 系统变量

条件判断case

create procedure 存储过程名称([in 参数名称 参数类型,out 参数名称 参数类型])
begin
    case
        when 条件1 then 逻辑1;
        when 条件2 then 逻辑2;
        when 条件3 then 逻辑3;
        ...
    end case;
end

示例:
创建存储过程

create procedure test10(in month int,out result varchar(30))
begin
case 
    when month >= 1 and month <= 3 then set result = "第一季度";
    when month >= 4 and month <= 6 then set result = "第二季度";
    when month >= 7 and month <= 9 then set result = "第三季度";
    when month >= 10 and month <= 12 then set result = "第四季度";
end case; 
    set result = concat("你输入的是第",month,"月份,它属于",result);
end 

调用

call test10(4,@result);

输出

select @result;

存储过程 – 循环

while循环

while 条件表达式 do

end while;

示例: 从1 加到 n的值

create procedure test11(in n int)
begin
    declare total int default 0;
    declare num int default 0;
    while num <= n do
        set total = total + num;
        set num = num + 1;
    end while;
    select total;
end

repeat循环

和while正好相反, 如果满足条件则退出循环

repeat

until 条件表达式
end repeat

示例: 从1 加到 n的值

create procedure test12(in n int)
begin
    declare total int default 0;
    repeat
        set total = total + n;
        set n = n - 1;
        until n = 0
    end repeat;
    select total;
end

loop循环

LOOP 实现简单的循环,退出循环的条件需要使用其他的语句定义,通常可以使用 LEAVE 语句实现,如果不在方法体内增加leave语句,则loop为死循环

标识符:loop
    
    if 条件表达式 then
        leave 标识符;
    end if;
    
    ....
    
end loop 标识符;

示例: 从1 加到 n的值

create procedure test13(in n int)
begin
    declare total int default 0;
    ins:loop
        if n <= 0 then
            leave ins;
        end if;
        
        set total = total + n;
       set n = n - 1;
   end loop ins; 
   
   select total;
end

存储过程 – 游标 / 光标

游标是用来存储查询结果集的数据类型
在存储过程和函数中可以使用光标对结果集进行循环的处理。
光标的使用包括光标的声明、OPEN、FETCH 和 CLOSE,

声明游标
declare 游标名称 cursor for SQL语句;

使用游标
open 游标名称;

获得光标
fetch 游标名称 into 变量1,变量2…

关闭游标
close 游标名称;

delimiter $
create procedure test0101()
begin
	declare id varchar(32);
	declare name varchar(33);
	declare has_data int default 1;
	declare students cursor for select * from student;
	declare exit handler for not fount set has_data = 0;
	open students;
	repeat
		fetch students into id,name;
		select concat("id:",id,",name:",name) as content;
		until has_data = 0
	end repeat;
	close students;
end $
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值