Mysql视图介绍
视图是一个存在于数据库中的虚拟表。视图本身没有数据,只是通过执行相应的select语句完成获得相应的数据。可以理解为select语句的别名。
(1).视图的作用
1.如果某个查询结果出现的非常频繁,即将这个查询结果作为子查询使用,视图能够简化用户的操作(简单性)
2.对数据提供安全保护(安全性)
3.对重构的数据库提供一定的逻辑性(逻辑数据独立性)
(2).创建视图
创建实验环境:
mysql> create database test_db; Query OK, 1 row affected (0.01 sec) mysql> use test_db; Database changed mysql> create table user_tb(id int,name varchar(20)); Query OK, 0 rows affected (0.03 sec) mysql> insert into user_tb values('1','zhangsan'),('2','lisi'); Query OK, 2 rows affected (0.11 sec) Records: 2 Duplicates: 0 Warnings: 0 mysql> select * from user_tb; +------+----------+ | id | name | +------+----------+ | 1 | zhangsan | | 2 | lisi | +------+----------+ 2 rows in set (0.00 sec)
create view [视图名] as [select查询语句];
mysql> create view st as select * from user_tb where id=1; Query OK, 0 rows affected (0.10 sec) mysql> select name from st; +----------+ | name | +----------+ | zhangsan | +----------+ 1 row in set (0.00 sec)
视图可以根据需求2次加工。
(3).修改视图
alter view [视图名] as [select语句];
mysql> alter view st as select * from user_tb where id=2; Query OK, 0 rows affected (0.01 sec) mysql> select name from st; +------+ | name | +------+ | lisi | +------+ 1 row in set (0.00 sec)
(4).删除视图
drop view [视图名];
mysql> drop view st; Query OK, 0 rows affected (0.01 sec) mysql> select * from st; ERROR 1146 (42S02): Table 'test_db.st' doesn't exist