zoukankan      html  css  js  c++  java
  • Mysql 2 视图、函数、存储过程和触发器

    第一部分、视图

    视图保存的是一段select查询语句,不保存实际数据,视图可以被当成一张表来查看,也可以增删改,会直接操作到原来的表上(只限于涉及单表的视图)。

    视图保存的是创建时的状态,如果修改了原表,视图不变动,但是如果删除某个字段,视图会报错。

    create view v_name as select * from students;
    select * from v_name;
    drop view v_name;

    第二部分、函数

    函数就是用来对数据进行一些操作的函数。

    一、操作符

    between .. and ...
    is null
    in (xx,xx,xx)

    二、常用函数

    greatest(10,20)  # 返回最大值
    isnull(10)  # 是否为null
    substring(str, 2, 3)  # 截取字符串从第二位开始的3位字符
    char_length(str)  # 返回字符串长度
    concat(str1, str2, str3)  # 拼接字符串
    concat_ws(',', str1, str2)  # 用,拼接字符串
    insert(str, 3, 4, xx)  # 将3-4为用xx替代
    instr(str, xx)  # 第一次出现xx的位置
    lower(xx)
    ltrim(xx)  # 去除左边的空白
    repeat(xx, 3)  # 重复三次
    replace(xx, xx, xx)  # 替换

    三、逻辑语句

    if(xx1, xx2, xx3)  # 如果xx1为true则返回xx2,否则返回xx3
    ifnull(xx, str)  # 如果xx为null则返回str
    case gender when 1 then 'male' else 'female' end;

    四、自定义函数

    delimiter //
    create function xxx(s CHAR(32)) RETURNS CHAR(32)
    begin
    RETURN concat('hello', s); end //
    delimiter ;

    第三部分、存储过程

    存储过程保存一段sql语句,通过call调用

    delimiter //
    create procedure xxx(IN param1 int, OUT param2 int)
    begin
    select count(*) INTO param2 from xxx where xx>param1;
    end //
    delimiter ;

    declare用来定义内部变量,但是只允许出现在begin后的第一行。

    delimiter //
    create procedure xxx(sid INT)
    begin
    declare x default 10;
    declare xname, xgender;
    select sname, gender INTO xname, xgender from xxx where sid=x;
    end //
    delimiter ;

    第四部分、触发器

    触发器就是让mysql取监听某个事件,当发生这个事件时就执行某些命令。

    DELIMITER ;;
    create trigger trigger_name before/after insert on tablename for each row
    begin
       xxxx
    end;
    DELIMITER ;

    第五部分、流程控制语句

    一、if

    if m > n then set s = '>';
    elseif m = n then set s = '=';
    else set s = '<';
    end if;

    二、case

    方式一
    case gender when 0 then 'male' when 1 then 'female' end case;
    
    方式二
    case when gender=0 then 'male' when gender != 0 then 'female' end case;

    三、while

    while xx do
        xxxx;
    end while;

    四、repeat

    repeat
        xxxx;
    until xxxx end repeat;
  • 相关阅读:
    xtrabackup增量备份mysql +MHA
    mysql备份恢复中的常见错误
    MySQL 面试题目
    Amoeba for MySQL 中间件
    [MySQLCPU]线上飙升800%,load达到12的解决过程
    pt-kill--- MySQL数据库CPU飙升紧急处理方法
    MySQL 5.7并行复制时代
    淘宝内部分享:怎么跳出MySQL的10个大坑
    Percona XtraBackup User Manual 阅读笔记
    淘宝内部分享:MySQL & MariaDB性能优化
  • 原文地址:https://www.cnblogs.com/yinwenjie/p/11687533.html
Copyright © 2011-2022 走看看