欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

SQL創(chuàng)建視圖的注意事項(xiàng)及說明

 更新時(shí)間:2023年02月07日 10:09:23   作者:AI_SupplyChain  
這篇文章主要介紹了SQL創(chuàng)建視圖的注意事項(xiàng)及說明,具有很好的參考價(jià)值,希望對大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教

視圖的創(chuàng)建和注意事項(xiàng)

如何創(chuàng)建視圖及注意事項(xiàng)

創(chuàng)建視圖圖的基本語法:

CREATE VIEW <視圖名稱>(<列名1>,<列名2>,...) AS 
<SELECT語句>
from  表名
group by 列名;-- 該語句可以選擇或者不寫該語句,兩者的區(qū)別就是是否有匯總

注意事項(xiàng):

  • 視圖名稱后面的列的數(shù)量必須與select 語句里面選擇的列的數(shù)量一致;否則會(huì)提示錯(cuò)誤;
  • 當(dāng)你創(chuàng)建了一個(gè)視圖后(同個(gè)視圖名字),若需要對視圖語句進(jìn)行修改的話,需要先刪除舊的視圖,否則會(huì)提示已有視圖;
  • select 語句里面的列與視圖里面的列是一一對應(yīng)的,視圖里面的列名可以根據(jù)需要自定義命名;
  • 刪除視圖語法: drop view 視圖名稱

例子:

案例1. with group by

drop view profit;
create view profit (種類,售價(jià), 進(jìn)價(jià),利潤)
As 
select product_type,sale_price,purchase_price,sale_price - purchase_price as profit
from product
group by product_type;

select * from profit;

結(jié)果如下:

案例2: without group by

drop view profit1;
create view profit1 (種類,售價(jià), 進(jìn)價(jià),利潤)
As 
select product_type,sale_price,purchase_price,sale_price - purchase_price as profit
from product; 
select * from profit1;

結(jié)果如下:

修改視圖結(jié)構(gòu)

修改視圖結(jié)構(gòu)的基本語法如下:

ALTER VIEW <視圖名> AS <SELECT語句>
-- 例如:
ALTER VIEW profit
    AS
        SELECT product_type, sale_price
          FROM Product
         WHERE regist_date > '2009-09-11';

mysql視圖的作用(詳細(xì))

  • 測試表:user有id,name,age,sex字段
  • 測試表:goods有id,name,price字段
  • 測試表:ug有id,userid,goodsid字段

視圖的作用實(shí)在是太強(qiáng)大了,以下是我體驗(yàn)過的好處:

作用一

提高了重用性,就像一個(gè)函數(shù)。如果要頻繁獲取user的name和goods的name。就應(yīng)該使用以下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;

但有了視圖就不一樣了,創(chuàng)建視圖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;

創(chuàng)建好視圖后,就可以這樣獲取user的name和goods的name。

示例:        

select * from other;

以上sql語句,就能獲取user的name和goods的name了。

作用二

對數(shù)據(jù)庫重構(gòu),卻不影響程序的運(yùn)行。假如因?yàn)槟撤N需求,需要將user拆房表usera和表userb,該兩張表的結(jié)構(gòu)如下:

  • 測試表:usera有id,name,age字段
  • 測試表:userb有id,name,sex字段

這時(shí)如果php端使用sql語句:select * from user;那就會(huì)提示該表不存在,這時(shí)該如何解決呢。

解決方案:創(chuàng)建視圖。

以下sql語句創(chuàng)建視圖:

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

以上假設(shè)name都是唯一的。此時(shí)php端使用sql語句:select * from user;就不會(huì)報(bào)錯(cuò)什么的。這就實(shí)現(xiàn)了更改數(shù)據(jù)庫結(jié)構(gòu),不更改腳本程序的功能了。

作用三

提高了安全性能??梢詫Σ煌挠脩?,設(shè)定不同的視圖。例如:某用戶只能獲取user表的name和age數(shù)據(jù),不能獲取sex數(shù)據(jù)。則可以這樣創(chuàng)建視圖。

示例如下:

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

這樣的話,使用sql語句:select * from other; 最多就只能獲取name和age的數(shù)據(jù),其他的數(shù)據(jù)就獲取不了了。

作用四

讓數(shù)據(jù)更加清晰。想要什么樣的數(shù)據(jù),就創(chuàng)建什么樣的視圖。經(jīng)過以上三條作用的解析,這條作用應(yīng)該很容易理解了吧

總結(jié)

以上為個(gè)人經(jīng)驗(yàn),希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。

相關(guān)文章

最新評論