目录视图的创建和注意事项如何创建视图及注意事项修改视图结构Mysql视图的作用(详细)作用一作用二作用三作用四总结视图的创建和注意事项 如何创建视图及注意事项 创建视图图的基本语法: CREATE VIEW <视图
创建视图图的基本语法:
CREATE VIEW <视图名称>(<列名1>,<列名2>,...) AS
<SELECT语句>
from 表名
group by 列名;-- 该语句可以选择或者不写该语句,两者的区别就是是否有汇总
注意事项:
例子:
案例1. with group by
drop view profit;
create view profit (种类,售价, 进价,利润)
As
select product_type,sale_price,purchase_price,sale_price - purchase_price as profit
from product
group by product_type;
select * from profit;
结果如下:
案例2: without group by
drop view profit1;
create view profit1 (种类,售价, 进价,利润)
As
select product_type,sale_price,purchase_price,sale_price - purchase_price as profit
from product;
select * from profit1;
结果如下:
修改视图结构的基本语法如下:
ALTER VIEW <视图名> AS <SELECT语句>
-- 例如:
ALTER VIEW profit
AS
SELECT product_type, sale_price
FROM Product
WHERE reGISt_date > '2009-09-11';
视图的作用实在是太强大了,以下是我体验过的好处:
提高了重用性,就像一个函数。如果要频繁获取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,该两张表的结构如下:
这时如果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的数据,其他的数据就获取不了了。
让数据更加清晰。想要什么样的数据,就创建什么样的视图。经过以上三条作用的解析,这条作用应该很容易理解了吧
以上为个人经验,希望能给大家一个参考,也希望大家多多支持我们。
--结束END--
本文标题: SQL创建视图的注意事项及说明
本文链接: https://www.lsjlt.com/news/194401.html(转载时请注明来源链接)
有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341
下载Word文档到电脑,方便收藏和打印~
2024-05-15
2024-05-15
2024-05-15
2024-05-15
2024-05-15
2024-05-15
2024-05-15
2024-05-15
2024-05-15
2024-05-15
回答
回答
回答
回答
回答
回答
回答
回答
回答
回答
0