1.使用视图的有点
重用sql
简化sql操作
保护数据。
创建视图,这样其实就把查询的结果都放在视图上了,然后以后直接使用就可以了。但是视图本身没有数据,如果更新视图,那么基表就会发生改变。
create view testview as select * from teacher
显示创建视图的语句
show create view testview
删除视图
drop view testview
更新视图
create or replace view
直接使用视图查询数据
select name from testview
并不是所有的视图都是可以更新的,mysql不能正确的确定被更新的基数据,比如有以下操作就不能操作:
分组 (group by 和having)
联结
子查询
并
聚集函数 (min() count() sum())
distinct
导出列
2.存储过程,简单说就是为以后使用而保存的一条或多条mysql语句的集合,可以视为批文件。
创建存储过程
默认的mysql的语句的分隔符都为;,如果命令行实用程序要解释存储过程自身内的;,那么就要临时改变实用程序的分隔符。
create procedure producting()
begin
select avg(tid) as count1 from teacher;
end;
修改分割符。这里的delimitter //是告诉实用程序使用//作为新的结束分隔符,存储过程中的;仍然保持不动,并且正确的传递给数据库引擎。最后一句话 delimiter ;就是将分隔符重新恢复为;
delimiter //
create procedure producting()
begin
select avg(tid) as count1 from teacher;
end //
delimiter ;
进行调用存储过程 ,其中in out表示的是输入输出
call producting();
删除存储过程,但是这样会报错
drop procedure producting;
可以换成
drop procedure if exists producting
设置带参数存储过程
delimiter //
create procedure production(
out count1 decimal(3,2)
)
begin
select avg(tid) into count1 from teacher;
end //
delimiter ;
#在这就是传递过去一个变量
call production(@c);
#然后进行查询显示
select @c
drop procedure production;
带in out的存储过程
delimiter //
create procedure production(
in num int,
out count1 decimal(8,2)
)
begin
select avg(tid)+num into count1 from teacher;
end //
delimiter ;
call production(100,@c);
select @c
drop procedure production
复杂的存储过程
delimiter //
create procedure production(
in num int,
in boo boolean,
out count1 decimal(8,2)
)
begin
if boo then
select avg(tid) from teacher into count1;
end if;
end //
delimiter ;
call production(100,true,@c)
call production(100,false,@c)
select @c
drop procedure production