1. 视图 创建视图 create vIEw 视图名字 as 查询SQL语句; drop vIEw 视图名字; alter vIEw 视图名字 as 查询SQL语句; 2. 触发器 1. 插入事件触发器 INSERT INTO order_table(gID,much) VALUES(1,3);
-- update goods set num = num -3 where ID =1;
CREATE TRIGGER tg1 AFTER INSERT on order_table for EACH row -- 固定写法 BEGIN update goods set num = num -new.much where ID =new.gID; END
-- 删除触发器 drop TRIGGER TG1; 2.更新事件触发器 update order_table set much = much +2 where oID = 6;
update goods set num = num+2 where ID = 1;
create TRIGGER tg2 AFTER UPDATE ON order_table for EACH ROW BEGIN update goods set num = num+old.much - new.much where ID = old.gID; END 3.删除事件触发器 DELETE FROM order_table where oID =6;
update goods set num = num + 3 where ID = 1;
create TRIGGER tg3 AFTER DELETE on order_table for EACH ROW BEGIN update goods set num = num + old.much where ID = old.gID; END 4.查看触发器 show tiggers;
3.存储过程 1.封装 -- CREATE PROCEDURE p1() -- BEGIN -- INSERT into goods VALUES (null,'韩涉',50); -- select * from goods; -- END --
call p1(); 2.参数 -- in out inout CREATE PROCEDURE p3(in i int,inout names varchar(50)) BEGIN update goods set name = names where ID = i; END
set @names = '大鹅';
call p2(4,@names);
select @names; into 使用 set @i = 0; set @n = ''; select num into @i from goods where ID = 1;
select @i; 3.判断 CREATE PROCEDURE p3(in flag char(5),in nums int) BEGIN if flag = 'true' then SELECT * from goods where num < nums; ELSEIF flag ='false' THEN SELECT * FROM goods where num > nums; ELSE SELECT * FROM goods; END if;
END call p3('false',20); 4.循环 -- 做 1-100 累加的和 create PROCEDURE p4(in n int,out he int) BEGIN declare i int DEFAulT 0; DECLARE sum int; set sum = 0; while i <= n DO set sum = sum +i; set i = i + 1;
end WHILE; set he = sum; end
set @he = 0;
call p4(100,@he);
select @he; 查看存储过程 show PROCEDURE status; 删除存储过程 drop PROCEDURE p1;
4.函数 create FUNCTION f1(x int,y int) RETURNS INT
BEGIN declare sum int DEFAulT 0; set sum = x +y; RETURN(sum); END
select f1(100,2);
select g.*,f1(100,num) FROM goods g;
DROP FUNCTION f1; 5.事物 什么是事物 一组SQL语句批量执行,要么全部执行成功,要么全部执行失败 事物的四个特点: 原子性:对于其数据修改,要么全都执行,要么全都不执行。 一致性:数据库原来有什么样的约束,事务执行之后还需要存在这样的约束,所有规则都必须应用于事务的修改,以保持所有数据的完整性。 隔离性:一个事务不能知道另外一个事务的执行情况(中间状态).所以同一个数据在有多个事物访问时,其中一个得到数据访问修改,其他的事物处于阻塞状态,直到数据被释放,轮到下一个使用。 持久性:即使出现致命的系统故障也将一直保持。不要告诉我系统说commit(提交)成功了,回头电话告诉我,服务器机房断电了,我的事务涉及到的数据修改可能没有进入数据库。 start TRANSACTION; -- 开启事物,关闭MysqL自己的自动提交方式 SAVEPOINT sa1;
update account set money = money -1000 where ID = 4;
SAVEPOINT sa1;
update account set money = money +1000 where ID = 3;
-- COMMIT; -- 提交当前事物 select * from account;
RolLBACK to sa1;-- 回滚当前事物 6.锁 当并发事务同时访问一个资源时,有可能导致数据不一致,因此需要一种机制来将数据访问顺序化,以保证数据库数据的一致性。 7.数据库的备份 备份: MysqLdump -uroot -p123456 数据库名 表 > 保存位置. 导入: MysqL> USE 数据库名; MysqL> source 备份文件.sql;
总结以上是内存溢出为你收集整理的MySQL:数据库入门篇4全部内容,希望文章能够帮你解决MySQL:数据库入门篇4所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)