mysql关于视图的用法以及作用

2019/04/09 21:36
阅读数 65

关于视图的用法以及作用。

作用一:

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

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;

但有了视图就不一样了,创建视图other。示例

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;

创建好视图后,就可以这样获取user的name和goods的name。示例:

select * from other;

以上sql语句,就能获取user的name和goods的name了。

作用二:

对数据库重构,却不影响程序的运行。假如因为某种需求,需要将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的数据,其他的数据就获取不了了。

转自http://baijiahao.baidu.com/s?id=1598694746553095044&wfr=spider&for=pc

展开阅读全文
加载中
点击引领话题📣 发布并加入讨论🔥
打赏
0 评论
0 收藏
0
分享
返回顶部
顶部