视图不是表,视图是虚表,视图依赖于表
视图存在目的:将频繁使用的select 语句保存提高效率,使用户看到的数据更加清晰,可选择对外展示部分数据以增强数据保密性,降低数据冗余
创建视图基本法:create view 视图名称(列名1,列名2)as select 语句
注意:视图名在数据库中需要是唯一的,不能与其他视图和表重名。一般的dbms中定义视图候不能使用orderBy语句
修改视图结构的基本语法如下
alter view 视图名 as select语句
更新视图的语法
update 视图名 set 列名=‘内容’
更新视图内容 就是对底层基础表的操作
对一个视图包含以下结构事是不可以更新的
聚合函数 sum,min,max,count等
distinct 关键字
group by 语句
having语句
HAVING 子句。
UNION 或 UNION ALL 运算符。
FROM 子句中包含多个表。
删除视图语法
drop view 视图名
子查询和视图关系
子查询是将用来定义视图的select语句直接用于from中 但是不像视图那样保存在存储介质汇总 执行完select语句后就消失了
子查询有嵌套子查询、标量子查询(标量就是单一的意思,单一即返回一个值)、关联子查询(关联子查询的执行过程 首先执行不带where的主查询 根据主查询结果匹配获取子查询结果 将主查询结果与子查询结果结合执行完整的sql语句
例如:选取出各商品种类中高于该商品种类的平均销售单价的商品 SELECT product_type, product_name, sale_price
FROM product ASp1
WHERE sale_price > (SELECT AVG(sale_price)
FROM product ASp2
WHERE p1.product_type =p2.product_type
GROUP BY product_type);)
函数
函数分为如下几类
1.算术函数 2 字符串函数 3日期函数 4 转换函数 5 聚合函数
算术函数:abs mod round
字符串函数:concat连接 (concat(str1,str2,str3)) length字符串长度 lower大小写转换 upper 大写转换 replace 字符串替换 (replace (对象字符串,替换前的字符串,替换后的字符串)substing 字符串截取 (substring(对象字符串from截取的起始位置 for 截取的字符数))substring_index(原始字符串,分隔符,n)
日期函数:current_date 获取当前日期 current_time 当前时间 current_timestamp 当前日期和时间 extract 截取日期元素(extract(日期元素 from 日期))
转化函数:cast 类型转换 cast(转换前 as 想要转化类型)coalesce 将null转化为其他值 coalesce(数据1,数据2,数据3…)
谓词 主要有 like between isnull isnotnull in exists

practice part1
q1:创建出满足下述三个条件的视图(视图名称为 ViewPractice5_1)。使用 product(商品)表作为参照表,假设表中包含初始状态的 8 行数据。

条件 1:销售单价大于等于 1000 日元。
条件 2:登记日期是 2009 年 9 月 20 日。
条件 3:包含商品名称、销售单价和登记日期三列
create view ViewPractice5_1
as select product_name,sale_price,regist_date from product where sale_price>=1000 and regist_date=‘2009-09-20’
q2:向创建的视图 ViewPractice5_1 中插入如下数据,会得到什么样的结果呢?
INSERT INTO ViewPractice5_1 VALUES (’ 刀子 ', 300, ‘2009-11-02’);
出现此视图无默认值
q3
select product_id,product_name,product_type,sale_price,(select avg(sale_price)from product) as sale_prcie_all from product
q4:

create view AvgPriceByType
as select product_id,product_name,product_type,sale_price ,avg_sale_price from (select product_id,product_name,product_type,sale_price,avg(sale_prcie) as avg_sale_price from product group by product_type) prodcut_sum
q5 按照销售单价( sale_price)对 product(商品)表中的商品进行如下分类。

低档商品:销售单价在1000日元以下(T恤衫、办公用品、叉子、擦菜板、 圆珠笔)
中档商品:销售单价在1001日元以上3000日元以下(菜刀)
高档商品:销售单价在3001日元以上(运动T恤、高压锅)
select sum(case when sale_price <=1000 then 1 else 0 end )as low_peice,sum(case when sale_price<=3000 and sale_price >=1001 then 1 else 0 end ) as mid_peice,sum(case when sale_price>=3001 then 1 else 0 end) as high_peice from product

更多推荐

学习sql查询方法视图