mysql關于視圖的用法以及作用
關于視圖的用法以及作用。
作用一:
提高了重用性,就像一個函數。如果要頻繁擷取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