MySQL高效编程学习笔记(八)--视图

多个相关联的复杂信息放在一张表中会导致数据的冗长性,可以分割为几个表之后用主键外键连接,但当需要连接的表非常多时,每次查询订单信息的SQL语句将变得非常复杂,导致查询的低效性和易错性,而视图可以解决这样的矛盾。视图的本质是将select语句的检索结果用用表的形式保存下来。注意:视图作用是将sql语句简化,但可能性能会下降,在使用多重视图时需要慎重。

  1. 创建视图
    CREAT VIEW 视图名(列名,…)AS SELECT 语句[WITH CHECK POINT];
    (1)建表
    注意:建表先建包含主键而不包含外键的表,不然会出错
    create table product(pid int primary key,pname varchar(50),price double);
    create table user(uid int primary key,zip varchar(50),address varchar(50),name varchar(50));
    create table order_detail(oid int primary key,pid int,quantity int,constraint fk_pid foreign key (pid) references product(pid));
    create table order_basic(oid int primary key,odate date,uid int,constraint fk_uid foreign key (uid) references user(uid));

在这里插入图片描述
(2)正常的连接的表查询方式(不用视图,这里乱码了,通过设置字符集为gbk可以解决)
select ob.oid as oid,ob.odate as odate,u.uid as uid,u.zip as zip,u.address as address,u.name as name,p.pid as pid ,p.pname as pname,p.price as price,od .quantity as quantity from(((order_basic as ob inner join order_detail as od on ob.oid=od.oid)inner join product as p on od.pid=p.pid)inner join user as u on ob.uid =u.uid)where ob.oid=1\G
在这里插入图片描述
(3)创建订单视图
create view v_order (oid,odate,uid,zip,address,name,pid,pname,price,quantity)as select ob.oid ,ob.odate,u.uid,u.zip,u.address,u.name,p.pid,p.pname,p.price,od.quantity from (((order_basic as ob inner join order_detail as od on ob.oid=od.oid)inner join product as p on od.pid=p.pid)inner join user as u on ob.uid=u.uid);
如果是替换已存在的视图,可将create改为replace
在这里插入图片描述
(4)删除视图 drop view 视图名
在这里插入图片描述
(5)确认订单视图的内容
Show tables;//此命令会显示创建的视图
在这里插入图片描述
查看详细信息用show fields
show fields from v_order ;
在这里插入图片描述
(6)使用视图检索订单(真方便O(∩_∩)O哈哈~)
select * from v_order where oid=1;
在这里插入图片描述
解决cmd上中文乱码set names gbk;
(7)使用视图增删查订单数据(因为一些原因,没法再cmd端存入中文数据)
insert into v_order(pid,pname,price) values(3,’’,34);
在这里插入图片描述
注意:以下条件不能增删查视图数据

  1. 视图列含有统计函数
  2. 视图定义时使用子查询
  3. 视图定义使用GROUP BY/HAVING/DISTINCT/UNION
  4. 进行跨越多个表操作
    (8)创建视图使用with check option命令
    该命令可以限制插入或者更新不符合视图检索的操作
    比如挑选单价大于300的数据作为视图,如果插入或更新小于300的数据,如果没加with check option,则插入更新成功(当数据更新为了之后),加了该语句则会报错。
    在这里插入图片描述
    sql未加with check option,
    在这里插入图片描述
    加with check option 后会检查sql语句是否满足创建视图的条件price>300
    在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/HuYingJie_1995/article/details/88683864