mysql视图的创建、基本操作、作用

一.mysql视图的创建

作用:提高了重用性,就像一个函数。如果要频繁获取user的name和goods的name。就应该使用以下sql语言。示例:

先创建3张表

1.1user表

1.2goods表

 1.3ug表,比如某某人有哪些食物

 

1.4创建视图  目的:查询某人有某食物

create view 视图名称 as 普通的查询语句;

create view other as select a.name as username, b.name as goodsname from user as a, goods as b, ug as c where a.id=c.userid and c.goodsid=b.id;

1.5查询视图

select * from other;

 

二:

    对数据库重构,却不影响程序的运行。假如因为某种需求,需要将user拆房表usera和表userb,该两张表的结构如下:

        测试表:usera有id,name,age字段

        测试表:userb有id,name,sex字段

    这时如果php端使用sql语句:select * from user;那就会提示该表不存在,这时该如何解决呢。解决方案:创建视图。以下sql语句创建视图:

        create view user as select a.name,a.age,b.sex from usera as a, userb as b where a.name=b.name;

        以上假设name都是唯一的。此时php端使用sql语句:select * from user;就不会报错什么的。这就实现了更改数据库结构,不更改脚本程序的功能了。

三:

    提高了安全性能,权限设置。可以对不同的用户,设定不同的视图。例如:某用户只能获取user表的name和age数据,不能获取sex数据。则可以这样创建视图。示例如下:

        create view other as select a.name, a.age from user as a;

    这样的话,使用sql语句:select * from other; 最多就只能获取name和age的数据,其他的数据就获取不了了。

四:

    让数据更加清晰。想要什么样的数据,就创建什么样的视图。经过以上三条作用的解析,这条作用应该很容易理解了吧

五.查询mysql有多少视图

show table  status  where  comment ='view';

六.如何删除视图

drop view视图名称;

七.对视图的dml操作

7.1增删改(dml):只能是单表操作

INSERT INTO other (username , goodsname) VALUES ("张三" , "苹果");

报错:> 1393 - Can not modify more than one base table through a join view 'test.other'

原因:无法通过联接视图“test.other”修改多个基表

八.视图的实质

虚拟表

猜你喜欢

转载自www.cnblogs.com/tongcc/p/11454282.html