视图的操作

#######################
#视图
################
--   视图保存的是select语句,大大节省空间 
--   视图的数据会随着原表的变化自动更新,
--   建议将经常使用的select语句做成视图 create view...as...
#################1.创建视图
create or replace view ProductSum(product_type,cnt_product)
as -- as不可以省略 
select product_type,count(*)
from Product
group by product_type;

################2. 使用视图(和表的操作类似)/查看视图  
show create view productsum;

select product_type,cnt_product
from ProductSum;


-- 多重视图 在视图的基础上再创建视图 
--    不要常使用,多重视图会降低sql的性能 

################3.修改视图
alter view productsum as
select product_type as '类型',count(*) as '合计'
from product group by product_type; 

################ 4.视图的限制  
#1.定义视图的时候不能使用order by 
#2.视图的更新 视图和表需要同时更新,因此通过汇总得到的视图无法进行更新
--     1:select语句有distinct,group by,having,order by,union,聚合函数
--     2:from子句包含多张表  
--     3:select语句中引用不可更新的视图

-- 上面的productsum视图就不能更新 因为视图和表无法同步(有group by)
-- 下面的视图可以更新
CREATE VIEW ProductJim (product_id, product_name, product_type, sale_price, purchase_price, regist_date) 
AS 
SELECT *  FROM Product WHERE product_type = '办公用品';
###############5.更新视图 此时product表也同步更新了
INSERT INTO ProductJim
VALUES ('0009', '印章', '办公用品', 95, 10, '2009-11-30'); 

update productjim set product_name = 'new' where product_id = '0001';



select * from ProductJim;
select * from Product;
delete from Product where product_id='0009';

###############6.删除视图  
drop view ProductSum;

猜你喜欢

转载自blog.csdn.net/kylin_learn/article/details/81141172