Mysql series fourteenth
Demand background
The leader of the e-commerce company said: Give me statistics: the total amount of orders for the month, the number of orders, the proportion of male and female orders, etc., we wrote a bunch of very complicated SQL, and then sent it to the leader.
Do you feel good about sending such a large piece of SQL to the leader?
If the leader only wants to see one of the data, you need to modify the SQL you sent. If the leader wants to add other statistical indicators in the future, you will send a large amount of SQL to the leader. For the leader, this SQL looks very complicated. , Difficult to maintain.
In fact, the leader does not care about how you achieve it. He only cares about these indicators, and it is easy to view and query, but you send the complex implementation to the leader.
So what can we do to hide these details and only expose concise results?
The database has helped us think about it: use views to solve this problem.
What is a view
concept
The view appeared after mysql5. It is a virtual table. The row and column data comes from some tables used when the view is defined. The data of the view is dynamically generated when the view is used. The view only saves the logic of sql , Do not save the results of the query.
scenes to be used
When the same query result is used in multiple places, and the query result is more complex, we can use the view to hide the complex implementation details.
The difference between views and tables
grammar | Whether it takes up physical space in practice | use | |
---|---|---|---|
view | create view | Just save the logic of sql | Add, delete, modify, and check, actually we only use queries |
table | create table | Saved data | Add, delete, modify |
Benefits of views
-
Simplify complex sql operations without knowing his implementation details
-
Isolate the original table, which can prevent people using the view from touching the original table, thereby protecting the original data and improving security
Prepare test data
There are a lot of test data, which I put on my personal blog.
Open the link in the browser: http://www.itsoku.com/article/209
Execute the script of the javacode2018_employees library part in mysql.
Successfully created the javacode2018_employees library and 5 tables as follows:
Table Name | description |
---|---|
departments | Department table |
employees | Employee Information Form |
jobs | Job Information Form |
locations | Location table (will be used in the department table) |
job_grades | Salary scale |
Create view
grammar
create view 视图名
as
查询语句;
Steps to use the view
-
Create view
-
Perform query operations on the view
Case 1
Query employee name, department, and type of work information that contains a character in the name
/*案例1:查询姓名中包含a字符的员工名、部门、工种信息*/
/*①创建视图myv1*/
CREATE VIEW myv1
AS
SELECT
t1.last_name,
t2.department_name,
t3.job_title
FROM employees t1, departments t2, jobs t3
WHERE t1.department_id = t2.department_id
AND t1.job_id = t3.job_id;
/*②使用视图*/
SELECT * FROM myv1 a where a.last_name like 'a%';
The effect is as follows:
mysql> SELECT * FROM myv1 a where a.last_name like 'a%';
+-----------+-----------------+----------------------+
| last_name | department_name | job_title |
+-----------+-----------------+----------------------+
| Austin | IT | Programmer |
| Atkinson | Shi | Stock Clerk |
| Ande | Sal | Sales Representative |
| Abel | Sal | Sales Representative |
+-----------+-----------------+----------------------+
4 rows in set (0.00 sec)
Above we created a view: myv1. When we need to look at the employee name, department, and type of work information, we don’t need to care about what the view looks like. We only need to query the view. SQL is much simpler.
Case 2
Case 2: Query the average salary level of each department
/*案例2:查询各部门的平均工资级别*/
/*①创建视图myv1*/
CREATE VIEW myv2
AS
SELECT
t1.department_id 部门id,
t1.ag 平均工资,
t2.grade_level 工资级别
FROM (SELECT
department_id,
AVG(salary) ag
FROM employees
GROUP BY department_id)
t1, job_grades t2
WHERE t1.ag BETWEEN t2.lowest_sal AND t2.highest_sal;
/*②使用视图*/
SELECT * FROM myv2;
effect:
mysql> SELECT * FROM myv2;
+----------+--------------+--------------+
| 部门id | 平均工资 | 工资级别 |
+----------+--------------+--------------+
| NULL | 7000.000000 | C |
| 10 | 4400.000000 | B |
| 20 | 9500.000000 | C |
| 30 | 4150.000000 | B |
| 40 | 6500.000000 | C |
| 50 | 3475.555556 | B |
| 60 | 5760.000000 | B |
| 70 | 10000.000000 | D |
| 80 | 8955.882353 | C |
| 90 | 19333.333333 | E |
| 100 | 8600.000000 | C |
| 110 | 10150.000000 | D |
+----------+--------------+--------------+
12 rows in set (0.00 sec)
Modify view
Way 1
If the view exists, modify it, if it does not exist, create a new view.
create or replace view 视图名
as
查询语句;
Example
CREATE OR REPLACE VIEW myv3
AS
SELECT
job_id,
AVG(salary) javg
FROM employees
GROUP BY job_id;
Way 2
alter view 视图名
as
查询语句;
Example
ALTER VIEW myv3
AS
SELECT *
FROM employees;
Delete view
grammar
drop view 视图名1 [,视图名2] [,视图名n];
Multiple views can be deleted at the same time, and multiple view names are separated by commas.
Example
mysql> drop view myv1,myv2,myv3;
Query OK, 0 rows affected (0.00 sec)
Query view structure
/*方式1*/
desc 视图名称;
/*方式2*/
show create view 视图名称;
Such as:
mysql> desc myv1;
+-----------------+-------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+-----------------+-------------+------+-----+---------+-------+
| last_name | varchar(25) | YES | | NULL | |
| department_name | varchar(3) | YES | | NULL | |
| job_title | varchar(35) | YES | | NULL | |
+-----------------+-------------+------+-----+---------+-------+
3 rows in set (0.00 sec)
mysql> show create view myv1;
+------+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+----------------------+----------------------+
| View | Create View | character_set_client | collation_connection |
+------+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+----------------------+----------------------+
| myv1 | CREATE ALGORITHM=UNDEFINED DEFINER=`root`@`localhost` SQL SECURITY DEFINER VIEW `myv1` AS select `t1`.`last_name` AS `last_name`,`t2`.`department_name` AS `department_name`,`t3`.`job_title` AS `job_title` from ((`employees` `t1` join `departments` `t2`) join `jobs` `t3`) where ((`t1`.`department_id` = `t2`.`department_id`) and (`t1`.`job_id` = `t3`.`job_id`)) | utf8 | utf8_general_ci |
+------+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+----------------------+----------------------+
1 row in set (0.00 sec)
show create view shows the view creation statement.
Update view [Basically not used]
The update of the view is to change the data in the view, not to change the sql logic in the view.
When the view is updated, the data in the original table will also be updated.
In order to prevent the data of the original table from being updated, you can add read-only permissions to the view, allowing only the view to be read, and not allowing the view to be updated.
Under normal circumstances, the view is rarely updated.
Example
CREATE OR REPLACE VIEW myv4
AS
SELECT last_name,email
from employees;
/*插入*/
insert into myv4 VALUES ('路人甲Java','[email protected]');
SELECT * from myv4 where email like 'javacode2018%';
/*修改*/
UPDATE myv4 SET last_name = '刘德华' WHERE last_name = '路人甲Java';
SELECT * from myv4 where email like 'javacode2018%';
/*删除*/
DELETE FROM myv4 where last_name = '刘德华';
SELECT * from myv4 where email like 'javacode2018%';
Note: We generally do not use the view update, just understand.