大数据闯关之MySQL进阶篇(四):视图-存储过程-触发器-灵析社区

秋叶无缘

写在前面

大家好,这里是立志于在有生之年看到并参与通用人工智能开发工作的Nobody,由于最近在公司要经常性地接触大数据工具,所以打算开一个大专栏对大数据工具进行学习总结整理。这部分接着之前的MySQL基础篇,接下来将对MySQL进阶部分进行学习。以下为该部分的前置博客

大数据闯关之MySQL进阶篇(一):存储引擎

大数据闯关之MySQL进阶篇(二):索引

大数据闯关之MySQL进阶篇(三):SQL优化

一、视图

  • 介绍:视图(View)是一种虚拟存在的表。视图中的数据并不在数据库中实际存在,行和列数据来自定义视图的查询中使用的表,并且是在使用视图时动态生成的
  • 创建
-- 创建视图
create or replace view stu_v_1 as select id, name from student where id <= 10;
  • 查询视图
-- 查询视图
show create view stu_v_1;
select * from stu_v_1;
  • 修改视图
-- 修改视图
create or replace view stu_v_1 as select id, name, no from student where id <= 10;
alter view test.stu_v_1 as select id, name, no from student where id <= 10;
  • 删除视图
drop view if exists stu_v_1;
  • 检查选项:当使用with check option子句创建视图时,MySQL会通过视图检查正在更改的每个行,以使其符合视图的定义。
create or replace view stu_v_1 as select id, name from student where id <= 10 with cascaded check option;
  • 视图的更新:要使得视图可更新,视图中的行与基础表中的行之间必须存在一对一的关系。如果视图包含以下任何一项,则该视图不可更新:

二、存储过程

  • 介绍:存储过程是事先经过编译并存储在数据库中的一段SQL语句的集合。存储过程可以对SQL语句进行封装和复用,类似于编程语言中的函数。
  • 特点
  • 创建
create procedure 存储过程名称([参数列表])
begin
	-- sql语句
end;
  • 调用
call 名称([参数])
  • 查看
select * from information_schema.ROUTINES where ROUTINE_SCHEMA='itcast'

show create procedure p1;
  • 删除
drop procedure if exists p1
  • 变量
  • if判断
create procedure p3()
begin
    declare score int default 58;
    declare result varchar(10);

    if score >= 85 then
        set result := '优秀';
    elseif score >= 60 then
        set result := '及格';
    else
        set result := '不及格';
    end if;
    select result;
end;
  • 参数
类型含义备注
IN该类参数作为输入,也就是需要调用时传入值默认
OUT该类参数作为输出,也就是该参数可以作为返回值
INOUT既可以作为输入参数,也可以作为输出参数
-- 根据传入的200分制的分数,进行换算,换算成百分制,然后返回
create procedure p5(inout score double)
begin
    set score := score * 0.5;
end;

set @score = 198;
call p5(@score);
select @score;
  • case
-- 根据传入的月份,判定月份所属的季节(要求采用case结构)。
-- 1-3月份,为第一季度
-- 4-6月份,为第二季度
-- 7-9月份,为第三季度
-- 10-12月份,为第四季度

create procedure p6(in month int)
begin
    declare result varchar(10);

    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 := '第四季度';
        else
            set result := '非法参数';
    end case ;

    select concat('您输入的月份为: ',month, ', 所属的季度为: ',result);
end;

·  循环

  • while
-- 计算从1累加到n的值,n为传入的参数值
create procedure p7(in n int)
begin
    declare total int default 0;
 
    while n>0 do
         set total := total + n;
         set n := n - 1;
    end while;
 
    select total;
end;
repeat


create procedure p8(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:可以配合LEAVE和ITERATE语句进行使用
create procedure p9(in n int)
begin
    declare total int default 0;
 
    sum:loop
        if n<=0 then
            leave sum;
        end if;
 
        set total := total + n;
        set n := n - 1;
    end loop sum;
 
    select total;
end;

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

-- 根据传入的参数uage,来查询用户表 tb_user中,所有的用户年龄小于等于uage的用户姓名(name)和专业(profession),
-- 并将用户的姓名和专业插入到所创建的一张新表(id,name,profession)中。
 
-- 逻辑:
-- A. 声明游标, 存储查询结果集
-- B. 准备: 创建表结构
-- C. 开启游标
-- D. 获取游标中的记录
-- E. 插入数据到新表中
-- F. 关闭游标
create procedure p11(in uage int)
begin
    declare uname varchar(100);
    declare upro varchar(100);
    declare u_cursor cursor for select name,profession from tb_user where age <= uage;
    declare exit handler for SQLSTATE '02000' close u_cursor;
 
    drop table if exists tb_user_pro;
    create table if not exists tb_user_pro(
        id int primary key auto_increment,
        name varchar(100),
        profession varchar(100)
    );
 
    open u_cursor;
    while true do
        fetch u_cursor into uname,upro;
        insert into tb_user_pro values (null, uname, upro);
    end while;
    close u_cursor;
 
end;

·  条件处理程序handler:可以用来定义在流程控制结构执行过程中遇到问题时相应的处理步骤。以上的循环中由于没有定义退出循环的条件,于是在游标遍历完所有的数据后就会报错,因此就需要用到条件处理程序

create procedure p12(in uage int)
begin
    declare uname varchar(100);
    declare upro varchar(100);
    declare u_cursor cursor for select name,profession from tb_user where age <= uage;
    declare exit handler for not found close u_cursor;
 
    drop table if exists tb_user_pro;
    create table if not exists tb_user_pro(
        id int primary key auto_increment,
        name varchar(100),
        profession varchar(100)
    );
 
    open u_cursor;
    while true do
        fetch u_cursor into uname,upro;
        insert into tb_user_pro values (null, uname, upro);
    end while;
    close u_cursor;
 
end;

.

三、存储函数

  • 存储函数是有返回值的存储过程,存储函数的参数只能是IN类型的
-- 从1到n的累加

create function fun1(n int)
returns int deterministic
begin
    declare total int default 0;

    while n>0 do
        set total := total + n;
        set n := n - 1;
    end while;

    return total;
end;

select fun1(50);
  • return type说明

四、触发器

·  介绍:触发器是与表有关的数据库对象,指在insert/update/delete之前或之后,触发并执行触发器中定义的sql语句集合。触发器这种特性可以协助应用在数据库端确保数据的完整性,日志记录,数据校验等操作

·  insert语法

-- 需求: 通过触发器记录 user 表的数据变更日志(user_logs) , 包含增加, 修改 , 删除 ;
 
-- 准备工作 : 日志表 user_logs
create table user_logs(
  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;
 
-- 插入数据触发器
create trigger tb_user_insert_trigger
    after insert on tb_user for each row
begin
    insert into user_logs(id, operation, operate_time, operate_id, operate_params) VALUES
    (null, 'insert', now(), new.id, concat('插入的数据内容为: id=',new.id,',name=',new.name, ', phone=', NEW.phone, ', email=', NEW.email, ', profession=', NEW.profession));
end;
 
-- 查看
show triggers ;
 
-- 删除
drop trigger tb_user_insert_trigger;
 
-- 插入数据到tb_user
insert into tb_user(id, name, phone, email, profession, age, gender, status, createtime) VALUES (26,'三皇子','18809091212','erhuangzi@163.com','软件工程',23,'1','1',now());
-- 修改数据触发器
create trigger tb_user_update_trigger
    after update on tb_user for each row
begin
    insert into user_logs(id, operation, operate_time, operate_id, operate_params) VALUES
    (null, 'update', now(), new.id,
        concat('更新之前的数据: id=',old.id,',name=',old.name, ', phone=', old.phone, ', email=', old.email, ', profession=', old.profession,
            ' | 更新之后的数据: id=',new.id,',name=',new.name, ', phone=', NEW.phone, ', email=', NEW.email, ', profession=', NEW.profession));
end;

show triggers ;

update tb_user set profession = '会计' where id = 23;

update tb_user set profession = '会计' where id <= 5;
  • delete语法
-- 删除数据触发器
create trigger tb_user_delete_trigger
    after delete on tb_user for each row
begin
    insert into user_logs(id, operation, operate_time, operate_id, operate_params) VALUES
    (null, 'delete', now(), old.id,
        concat('删除之前的数据: id=',old.id,',name=',old.name, ', phone=', old.phone, ', email=', old.email, ', profession=', old.profession));
end;

show triggers ;


delete from tb_user where id = 26;




阅读量:1943

点赞量:0

收藏量:0