本博文源于mysql基础,旨在对视图进行学习与练习。涉及创建单表/多表视图,查询视图,修改视图,修改视图内容,删除视图.
在学习章节之前,需要先创建两张表,然后再插入记录。
create table tb_students_info
(id INT(11) PRIMARY KEY,
name VARCHAR(10),dept_id INT(11),
age INT(11),sex VARCHAR(4),height FLOAT,login_date DATE);
然后插入记录
insert into tb_students_info values(1,'Dany',1,25,'F',160,'2015-09-10');
insert into tb_students_info values(2,'Green',3,23,'F',158,'2016-10-22');
insert into tb_students_info values(3,'Henry',2,23,'M',159,'2016-10-23');
insert into tb_students_info values(4,'Jane',1,22,'F',156,'2016-10-12');
insert into tb_students_info values(5,'Jim',1,24,'M',158,'2016-10-22');
insert into tb_students_info values(6,'John',2,21,'M',152,'2016-10-24');
insert into tb_students_info values(7,'Lily',6,22,'F',160,'2016-10-25');
insert into tb_students_info values(8,'Susan',4,23,'F',166,'2016-10-26');
insert into tb_students_info values(9,'Green',3,22,'M',170,'2016-10-27');
insert into tb_students_info values(10,'Green',4,23,'M',193,'2016-10-23');
我们还需要一个tb_departments
create table tb_departments (dept_id int(11) primary key,dept_name varchar
(11),dept_call int(11),dept_type varchar(2));
insert into tb_departments values(1,'Computer',11111,'A');
insert into tb_departments values(2,'Math',22222,'A');
insert into tb_departments values(3,'Chinese',33333,'B');
insert into tb_departments values(4,'Economy',44444,'B');
insert into tb_departments values(5,'History',55555,'B');
有了它们,我们可以往下做练习
视图是一个虚拟表,其内容由查询定义。同真实表一样,视图包含一系列带有名称的列和行数据,但视图并不是数据库真实存储的数据表。
CREATE VIEW <视图名> AS <SELECT 语句>
create view view_students_info as select * from tb_students_info;
create view vi_students_info (s_id,s_name,d_id,s_age,s_sex,s_height,s_date) as
SELECT id,name,dept_id,age,sex,height,login_date from tb_students_info;
格式DESCRIBE 视图名
describe vi_students_info;
可以使用ALTER VIEW语句来对已有的视图进行修改。
VIEW <视图名> AS <SELECT 语句>
不能修改视图的地方有很多,但大家只需要记住UPDATE、DELETE、INSERT能修改视图。
ALTER VIEW vi_students_info as select id,name,age from tb_students_info;
update vi_students_info set age=28 where id=5;
delete from vi_students_info where id=5;
DROP VIEW <视图名1> [,<视图名2>...]
drop view vi_students_info;