【⑮MySQL | View】Overview|Create|View|Update|Modify|Delete

foreword

✨Welcome to Xiao K 's MySQL column , this section will bring you an overview of MySQL views | create | view | update | modify | delete sharing


1. View overview

insert image description here

1.1 Why use views?

On the one hand, the view can help us use a part of the table instead of the entire table, and on the other hand, it can also set different query views for different users. For example, for the company's salesperson, we only want to show him some data, and some special data, such as purchase price, will not be provided to him. For another example, employee salary is a sensitive field, so it is only open to personnel above a certain level, and this field is not provided in other people's query views.

1.2 View understanding

  • A view is 虚拟表, by itself 不具有数据, a very small memory footprint, and it's an important concept in SQL.
  • Views are built on the basis of existing tables, and these tables on which the view is built are called base tables .

insert image description here

  • The creation and deletion of a view only affects the view itself, not the corresponding base table. But when adding, deleting and modifying the data in the view, the data in the base table will change accordingly, and vice versa.
  • The statement that provides data content to the view is SELECTa statement, and the view can be understood as a stored SELECTstatement
  • A view is another form of expression that provides users with base table data. Under normal circumstances, the database of a small project does not need to use a view, but in a large project, and when the data table is more complex, the value of the view is highlighted, which can help us put the frequently queried result set into a virtual table , improve usage efficiency. It is very convenient to understand and use.

2. Create a view

2.1 View Syntax

  • Complete create view syntax
CREATE [OR REPLACE] [ALGORITHM = {UNDEFINED | MERGE | TEMPTABLE}] 
VIEW 视图名称 [(字段列表)] 
AS 查询语句 
[WITH [CASCADED|LOCAL] CHECK OPTION]
  1. CREATE [OR REPLACE]:Create views. Optionally use ``OR REPLACE`' to replace an existing view with the same name.
  2. [ALGORITHM = {UNDEFINED | MERGE | TEMPTABLE}]:Optional parameter to specify the view's algorithm. UNDEFINEDIndicates to let MySQL automatically select the algorithm, MERGEindicates to use the merge algorithm, and TEMPTABLEindicates to use the temporary table algorithm.
  3. VIEW view name: Specify the name of the view to create.
  4. [(field list)]: Optional parameter, specifying the column names to display in the view. If not specified, the view will contain all query result columns.
  5. AS query statement: specify the query statement used to create the view. The query statement can include operations such as JOIN, WHERE, and GROUP BY to filter and connect data.
  6. [WITH [CASCADED|LOCAL] CHECK OPTION]:Optional parameter to specify inspection options for the view. CASCADED means to check all related views, and LOCAL means to check only the current view.
  • ultra-simplified version
CREATE VIEW 视图名称
AS 查询语句

2.2 Create a single table view

Example : Create a view "v_emp1" that displays the employee's name, job, and salary.

CREATE VIEW v_emp1
AS
SELECT ename,job,sal FROM emps;

Query view:

SELECT * FROM v_emp1;

For the processing of aliases, you can specify the corresponding aliases in the subquery that creates the view

CREATE VIEW v_emp1_1
AS
SELECT ename 姓名,job 工作,sal 薪资 FROM emps;

You can also add the corresponding alias field after the view name of the created view

CREATE OR REPLACE VIEW v_emp1_2(姓名,工作,薪资)
AS
SELECT ename,job,sal FROM emps;

When we create a view, we can also encapsulate the field that does not exist in the base table

Example : create a view "v_emp2", display the number of each department, and the average salary

CREATE VIEW v_emp2(deptno,avg_sal)
AS
SELECT deptno,AVG(sal) FROM emps GROUP BY deptno;

2.2 Create a multi-table view

The above is a view created based on a single table. Of course, we can also encapsulate it as a corresponding view based on the results of multi-table queries.

Example : Create a view "v_emp_dept" to display the department number and the number of people in the department

CREATE VIEW v_emp_dept
AS 
SELECT d.deptno,COUNT(d.deptno)
FROM emps e JOIN depts d
ON e.deptno=d.deptno GROUP BY d.deptno;

query view

SELECT * FROM v_emp_dept;

Of course, the handling of aliases is also applicable to multiple tables.

2.3 Create views based on views

After we create a view, we can continue to create views based on it.

CREATE VIEW v_sal_personNum
AS
SELECT v1.deptno,v1.avg_sal,v2.dPersonNum FROM v_emp2 v1 JOIN v_emp_dept v2 ON v1.deptno=v2.deptno;

view view

select * from v_sal_personNum;

At this point, we can actually find that the creation of views is still very flexible.

3. View view

Syntax 1: View the table object and view object of the database

SHOW TABLES;

Syntax 2: View the structure of a view

DESC/DESCRIBE 视图名称;

Syntax 3: View attribute information of a view

# 查看视图信息(显示数据表的存储引擎、版本、数据行数和数据大小等)
SHOW TABLE STATUS LIKE '视图名称';

The execution result shows that the Comment is VIEW, indicating that the table is a view, and other information is NULL, indicating that this is a virtual table .

Syntax 4: View detailed definition information of a view

SHOW CREATE VIEW 视图名称;

4. Update view data

4.1 General situation

MySQL supports the use of INSERT, UPDATE, and DELETE statements to insert, update, and delete data in views. When the data in the view changes, the data in the data table also changes, and vice versa.

Example : Change the salary of the employee named 'WARD' to 1234 through the view v_emp1.

#更新视图的数据,基表中的数据也会修改
UPDATE v_emp1 SET sal=1234 WHERE name='WARD';
#更新基本中的数据,视图中的数据也会修改
UPDATE emps SET sal=1000 WHERE name='WARD';

Example : Delete the employee named 'WARD' through the view v_emp1

DELETE FROM v_emp1 WHERE name='WARD';

4.2 Non-updatable views

For a view to be updatable, there must be a one-to-one relationship between the rows in the view and the rows in the underlying base table. In addition, when the view definition has the following conditions, the view does not support the update operation:

  • When "ALGORITHM = TEMPTABLE" is specified when defining the view, the view will not support INSERT and DELETE operations;
  • The view does not contain all the columns in the base table that are defined as non-null and do not specify a default value, and the view will not support INSERT operations;
  • If the JOIN query is used in the SELECT statement defining the view, the view will not support INSERT and DELETE operations;
  • If a mathematical expression or subquery is used in the field list after the SELECT statement defining the view, the view will not support INSERT or UPDATE field values ​​using mathematical expressions or subqueries;
  • Use DISTINCT, aggregate functions, GROUP BY, HAVING, UNION, etc. in the field list after the SELECT statement that defines the view, and the view will not support INSERT, UPDATE, DELETE;
  • If a subquery is included in the SELECT statement defining the view, and the table behind FROM is referenced in the subquery, the view will not support INSERT, UPDATE, DELETE;

Example : Change the average salary of department 20 to 5000 through the view v_emp2 (the view that counts the average salary)

UPDATE v_emp2 SET avg_sal=5000 WHERE deptno=20;
-- The target table v_emp2 of the UPDATE is not updatable

DELETE FROM v_emp2 WHERE deptno=10;
-- The target table v_emp2 of the DELETE is not updatable

Note: Although the view data can be updated, in general, the view is a virtual table, which is mainly used to facilitate query, and it is not recommended to update the view data. Changes to view data are all done through operations on the data in the actual data table.

5. Modify the view

Method 1: Use the CREATE OR REPLACE VIEW clause to modify the view

CREATE OR REPLACE VIEW v_emp1
AS 
SELECT ename,job,sal FROM emps WHERE deptno=20;

Method 2: ALTER VIEW

ALTER VIEW v_emp1
AS 
SELECT ename,job,sal FROM emps WHERE deptno=10;

6. Delete view

Deleting a view only deletes the definition of the view, and does not delete the data in the base table.

The syntax for deleting a view is:

DROP VIEW IF EXISTS 视图名称;
DROP VIEW IF EXISTS 视图名称1,视图名称2,视图名称3,...;

Example:

DROP VIEW v_emp1;

Explanation: A new view c is created based on views a and b. If view a or view b is deleted, the query of view c will fail. Such view c needs to be manually deleted or modified, otherwise it will affect the use.

Summarize

In general, views in MySQL provide a convenient, flexible and safe way to handle complex query operations, and provide the benefits of data protection and performance optimization ~The next section brings the sharing of stored procedures and functions

Guess you like

Origin blog.csdn.net/qq_72157449/article/details/132451304