MySQL 视图
前言
本环境是基于 Centos 7.8 系统构建MySQL-5.7.14
具体构建,请参考 MySQL-5.7.14 环境构建
经常要对emp和dept表进行连接查询,每次都要做表的连接,写同样的一串语句,同时由于工资列队数据比较敏感,对外要求不可见。
这样,我们可以通过创建视图来完成
视图的特征
- 视图通过以定制的方式显示来自一个或多个表的数据
- 视图是一种数据库对象,用户可以像查询普通表一样查询视图,视图内其实没有存储任何数据,它只是对表的一个查询
- 视图的定义保存在数据字典内,创建视图所基于对表称为"基表”
视图的优点
作用:
- 控制安全
- 保存查询数据
优点:
- 提供了灵活一致级别安全性。
- 隐藏了数据的复杂性
- 简化了用户的SQL指令
- 通过重命名列,从另一个角度提供数据
创建表
mysql> CREATE TABLE college(
-> number INT(10) NOT NULL UNIQUE PRIMARY KEY COMMENT '学号',
-> name VARCHAR(20) NOT NULL COMMENT '姓名',
-> major VARCHAR(20) NOT NULL COMMENT '专业',
-> age INT(5) COMMENT '年龄'
-> )
表中插入数据
Query OK, 0 rows affected (0.18 sec)
mysql> INSERT INTO college_view VALUES(0901,'张三',20,'外语');
Query OK, 1 row affected (0.11 sec)
mysql> INSERT INTO college_view VALUES(0902,'李四',22,'计算机');
Query OK, 1 row affected (0.00 sec)
mysql> INSERT INTO college_view VALUES(0903,'王五',19,'计算机');
Query OK, 1 row affected (0.00 sec)
创建视图
mysql> create
-> algorithm = merge
-> view college_view(student_num,student_name,student_age,department)
-> as
-> select number,name,age,major
-> from college
-> with local check option;
Query OK, 0 rows affected (0.18 sec)
查看视图
mysql> select * from college_view;
+-------------+--------------+-------------+------------+
| student_num | student_name | student_age | department |
+-------------+--------------+-------------+------------+
| 901 | 张三 | 20 | 外语 |
| 902 | 李四 | 22 | 计算机 |
| 903 | 王五 | 19 | 计算机 |
+-------------+--------------+-------------+------------+
3 rows in set (0.00 sec)
修改视图
mysql> alter
-> algorithm = merge
-> view college_view(student_num,student_name,student_age,department)
-> as
-> select number,name,age,major
-> from college
-> where major='计算机'
-> with local check option;
Query OK, 0 rows affected (0.00 sec)
再次查看视图
mysql> select * from college_view;
+-------------+--------------+-------------+------------+
| student_num | student_name | student_age | department |
+-------------+--------------+-------------+------------+
| 902 | 李四 | 22 | 计算机 |
| 903 | 王五 | 19 | 计算机 |
+-------------+--------------+-------------+------------+
2 rows in set (0.00 sec)