视点集中sql
简化操做数据库
定制数据安全
合并分割数据app
安全性spa
视图是存储在数据库中的查询的sql 语句,它主要出于两种缘由:code
安全缘由,视图能够隐藏一些数据,如社会保险基金表,能够用视图只显示姓名,地址,而不显示社会保险号和工资数等,htm
可以使复杂的查询易于理解和使用。get
CREATE VIEW view_name AS SELECT column_name(s) FROM table_name WHERE condition
[注]:视图老是显示最近的数据。每当用户查询视图时,数据库引擎经过使用 SQL 语句来重建数据。qt
CREATE OR REPLACE VIEW view_name AS SELECT column_name(s) FROM table_name WHERE condition
DROP VIEW view_name
product 表it
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());
create view purchase_detail as select product.name as name, product.price as price, purchase.qty as qty, product.price * purchase.qty as total_value from product, purchase where product.product_id = purchase.product_id;
select * from purchase_detail;
注意事项
运行建立视图的语句须要用户具备建立视图(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;