MySQL view
Preface
This environment is based on Centos 7.8 system to build MySQL-5.7.14 for
specific construction, please refer to MySQL-5.7.14 environment construction
It is often necessary to perform a join query on the emp and dept tables, each time the tables are joined, and the same string of statements are written. At the same time, because the salary queue data is more sensitive, external requirements are not visible.
In this way, we can complete by creating a view
View characteristics
- The view displays data from one or more tables in a customized way
- A view is a database object. Users can query the view like a normal table. In fact, there is no data stored in the view. It is just a query on the table.
- The definition of the view is stored in the data dictionary, and the table on which the view is created is called the "base table"
Advantages of views
effect:
- Control security
- Save query data
advantage:
- Provides a flexible and consistent level of security.
- Hide the complexity of the data
- Simplify the user's SQL commands
- Provide data from another angle by renaming columns
Create table
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 '年龄'
-> )
Insert data into the table
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)
Create view
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)
View view
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)
Modify view
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)
Look at the view again
mysql> select * from college_view;
+-------------+--------------+-------------+------------+
| student_num | student_name | student_age | department |
+-------------+--------------+-------------+------------+
| 902 | 李四 | 22 | 计算机 |
| 903 | 王五 | 19 | 计算机 |
+-------------+--------------+-------------+------------+
2 rows in set (0.00 sec)