檢視表 (View) « 關於網路那些事...
阿新 • • 發佈:2018-12-29
檢視表是一個虛擬的資料表,從MySQL 5.0.1 版本即開始支援
在使用時,設計者可自行將多個表格進行關聯、篩選,製作成一份獨立的檢視表
使用上,具有以下優點
- 簡單明瞭: 使用者不需要理解整個資料結構,直接呼叫檢視表就能取得整合完成的資料
- 安全: 使用者僅能看到檢視表允許查詢的部分
- 獨立: 檢視表結構會彙整關聯的資料表,當關聯資料表新增資料時,也能同時取得;僅有當關聯表修改列名時,才需要調整檢視表的結構對應名稱
建立檢視表
刪除檢視表
檢視檢視表
更新檢視表
檢視表對於更新資料有諸多限制,
在一般單純 SELECT 的檢視表,可執行 UPDATE 功能
但是有用到 sum, min, max,count, distinct, group by, having, union.... 等函式,都無法執行更新
在這裡還是建議,檢視表盡量僅用於檢視功能,如果需要進一步的操作,應該使用其他方式
檢視檢視表定義
檢視表中建立檢視表
在MySQL 檢視表的定義存在一些限制,包括 FROM 之後不能有子查詢,使用 sum, min, max,count, distinct, group by, having, union.... 等函式,都無法執行更新..等
雖然FROM 之後不能有子查詢,還是可以先將子查詢建立成檢視表,就能實現
對於檢視表中使用檢視表的方式,
在更新資料時,可以搭配 CASCADED 與 LOCAL 這兩個檢查選項
-
CASCADED : 檢視表必須連同滿足內部依賴檢視表的條件,才可更新本檢視表 (預設選項,若無指定名稱則預設為CASCADED)
-
LOCAL : 檢視表不須考慮內部依賴檢視表的條件,即可更新本檢視表
CHECK OPTION 範例
建立表單,並且插入數值9
建立三個view
- main_view 指定 i < 10, 未指定CHECK OPTION (預設為CASCADED)
- main1_view 指定 i > 5,指定為CASCADED CHECK OPTION
- main2_view 指定 i > 5,指定為LOCAL CHECK OPTION
接著,試著更新資料,將 9 更新為 10 的情況
在 main1_view 會發生錯誤, main2_view 則更新成功
因為 main1_view 指定為CASCADED,需要同時檢查依賴檢視表的規則
main2_view 指定為 LOCAL ,只會檢查自己檢視表的規則,不會檢查依賴檢視表
ex
如果你喜歡我們的文章內容,請在這裡按個讚
Tweet