標籤:
<一> 視圖
1.優點
視點集中
簡化操作
定製資料
合并分割資料
安全性
2.為什麼需要視圖?
視圖是儲存在資料庫中的查詢的sql 語句,它主要出於兩種原因:
3.建立視圖的文法
CREATE VIEW view_name AS SELECT column_name(s) FROM table_name WHERE condition
[注]:視圖總是顯示最近的資料。每當使用者查詢檢視時,資料庫引擎通過使用 SQL 陳述式來重建資料。
4.更新視圖的文法
CREATE OR REPLACE VIEW view_name AS SELECT column_name(s) FROM table_name WHERE condition
5.刪除視圖的文法
DROP VIEW view_name
<二>例子1.建立兩張表,並插入資料
product 表
create table product ( product_id int not null, name varchar(50) not null, price double not null ); insert into product values(1, ‘apple ‘, 5.5);
purchase 表
create table purchase ( id int not null, product_id int not null, qty int not null default 0, gen_time datetime not null ); insert into purchase values(1, 1, 10, now());
2.建立視圖:
create view purchase_detail as select product.name as name, product.price as price, purchase.qty as qty, product.price * purchase.qty as total_valuefrom product, purchase where product.product_id = purchase.product_id;
3.建立視圖後,查詢:
select * from purchase_detail;
4.結果:
<三>.建立視圖的注意事項
注意事項
運行建立視圖的語句需要使用者具有建立視圖(crate view)的許可權,若加了[or replace]時,還需要使用者具有刪除視圖(drop view)的許可權;
select語句不能包含from子句中的子查詢;
select語句不能引用系統或使用者變數;
select語句不能引用預先處理語句參數;
在儲存子程式內,定義不能引用子程式參數或局部變數;
在定義中引用的表或視圖必須存在。但是,建立了MySQL視圖後,能夠捨棄定義引用的表或視圖。要想檢查視圖定義是否存在這類問題,可使用check table語句;
在定義中不能引用temporary表,不能建立temporary視圖;
在視圖定義中命名的表必須已存在;
不能將觸發程式與視圖關聯在一起;
在視圖定義中允許使用order by,但是,如果從特定視圖進行了選擇,而該視圖使用了具有自己order by的語句,它將被忽略。
<四>.修改視圖
使用 alter view
alter view purchase_detail as select product.name as name, product.price as price, product.price * purchase.qty as total_value from product, purchase where product.product_id = purchase.product_id;
參考:http://database.51cto.com/art/201005/200526.htm
MySQL 檢視使用初探