MySql
MySql
视图
由一张表或多张表导出的虚拟表
简化SQL语句, 每次执行的时候其实都是执行SQL语句, 不会提高性能
create view myview as(SQL语句); // 为SQL语句代表的表创建一个名称为myview的试图, 之后就可以把myview当作表使用
drop * from myview; # 删除视图
一般用视图查询
很少用视图更改
函数
drop function if exists myfun; # 如果函数存在就删除
delimiter // create function myfun(a int, b int) # 函数名和参数, 默认参数为in类型 returns int # 返回值类型 begin # 函数体 declare c int default 0; # 声明局部变量c set c = a + b; # 给c赋值 return c; # end // # 函数体结束 delimiter ; #delimiter 重写结束符, 一开始分号是结束符, 重写为 // , 函数结束后在将结束符重写为分号, 该语句后面不能加注释
会话变量
一直到当前会话结束
set @a = myfun(4, 5); # 将函数返回值赋值给会话变量, 以@开头
系统变量
@@开头, root用户可以定义
删除函数
drop function myfun;
函数中不能使用SQL语句
条件语句
if (a > 0) then set c = 'test_1'; elif (a = 0) then set c = 'test_2'; else set c = 'test_3'; end if;
case when a > 0 then ...; when a = 0 then ...; else ...; end case;
case a when 1 then ...; when 2 then ...; when 3 then ...; else ...; end case;
循环
三种:while、repeat、loop
while i <= a # 循环条件, 死循环:1 = 1 do # 循环体开始 set snum = snum + i; set i = i + 1; end while; # 循环结束
跳出循环
out_label : begin while ... if (i > a) then leave out_label; # 跳出循环到end out_label处 end if; end while end out_label;
存储过程
封装SQL语句, 功能比函数强
drop procedure if exists myproc; # 如果存在就删除
delimiter // create procedure myproc(out a int) #参数可以是in / inout / out, 可以通过参数返回值 begin select * from user; end // delimiter ;
调用
call myproc(@a);
触发器
是一种特殊的存储过程, 当指定事件发生的时候, 系统自动调用
# 触发器自动产生两张表, new更改后的数据, old原始数据 delimiter // create trigger myinsert after insert # 对表执行的操作, before/after, 插入前, 插入后 on user # 作用在哪一个表 for each row begin insert into userstate values(new.u_id, 0, now()); # 利用new表中的数据 end delimiter ;
删除
drop trigger myinsert;
事务
一组命令要么都成功执行, 要么都不执行, 失败会回滚到未执行状态。
start transaction; # aa向bb转60 update bank set money = money - 60 where name = 'aa'; update bank set money = money + 60 where name = 'bb'; relback; # 如果失败就回滚
原子性
一组事物, 要么成功, 要么撤回
稳定性
如果有非法数据, 事物撤回
隔离性
一个事务影响了其他事务, 其他事务会撤回
事务的100%隔离, 需要牺牲速度
可靠性
崩溃后, InnoDB数据表驱动会利用日志文件重构修改
索引
提高表的查询效率
聚集索引/非聚集索引
用B+Tree实现
游标

浙公网安备 33010602011771号