一、视图
虚拟表,和普通表一样使用
mysql5.1版本出现的新特性,是通过表动态生成的数据
优点:
简化sql、提高了sql的重用性、保护基表的数据,提高了安全性
1、创建视图
语法:
create view 视图名 as 查询语句;
2、视图的修改
方式一:
create or replace view 视图名 as 查询语句;(如果视图存在就修改,不存在就创建)
方式二:
alter view 视图名 as 查询语句;
3、删除视图
drop view 视图1,视图2,.......;(可一次性删除多个视图)
4、查看视图
desc 视图名;
show create view 视图名;
5、视图的更新(已有视图数据更新,会更新原始表数据)
插入:insert into
修改:update
删除:delete from
视图的可更新和视图中查询的定义有关系,以下类型的视图是不能更新的:
包含以下关键字:分组函数、distinct、group by、having、union或union all
常量视图(常量:select 'john' name;)
select中包含子查询
join
from一个不能更新的视图
where子句的子查询引用了from子句中的表(where子查询语句用到的表和from中指定的表相同)
 
-- 1、创建表Book表,字段如下: bid 整型,要求主键
-- bname 字符型,要求设置唯一键,并非空 
-- price 浮点型 ,要求有默认值10
-- btypeld 类型编号,要求引用bookType表的 id字段
-- 已知bookType表(不用创建),字段如下: id name
use books;
create table if not exists bookType(id int primary key,name varchar(20));
create table if not exists book(
bid int primary key,
bname varchar(50) unique not null,
price float default 10,
btypeld int,
constraint fk_bookType_book foreign key(btypeld) references bookType(id)
);
show index from book;
show create table book;
-- 2、开启事务向表中插入1行数据,并结束
set autocommit=0;
show variables like '%autocommit%';
insert into bookType values(1,'思维');
insert into book values(1,'天才在左,疯子在右',28,1);
commit;
select * from book;
-- 3、创建视图,实现查询价格大于100的书名和类型名
insert into book values(2,'爱你在心尖',128,1);
create view Price_greater_than_100 as select bname,name from book b join bookType bt on b.btypeld=bt.id where price>100;
select * from Price_greater_than_100;
-- 4、修改视图,实现查询价格在90-120之间的书名和价格
insert into book values(3,'稻城',90,1);
-- 修改视图
create or replace view Price_greater_than_100 as select bname,name from book b join bookType bt on b.btypeld=bt.id where price BETWEEN 90 and 120;
-- 修改视图
alter view Price_greater_than_100 as select bname,name from book b join bookType bt on b.btypeld=bt.id where price BETWEEN 90 and 120;
-- 5、删除刚才建的视图
drop view Price_greater_than_100,price_greater_than_100_and_120;

 

posted on 2022-07-17 22:13  时光以北暮南城  阅读(59)  评论(0编辑  收藏  举报