当前位置:网站首页>Summary of MySQL foundation view
Summary of MySQL foundation view
2022-06-12 22:59:00 【Jingxuan】
View summary table of contents
1. View overview
1.1 Common database objects
| object | describe |
|---|---|
| surface (TABLE) | A table is a logical unit that stores data , Exist as rows and columns , Columns are fields , Line is the record |
| The data dictionary | The system tables , A table that holds database related information . The data of the system table is usually maintained by the database system , Programmers usually shouldn't modify , You can only view |
| constraint (CONSTRAINT) | Rules for performing data verification , Rules for ensuring data integrity |
| View (VIEW) | Logical display of data in one or more datasheets , Views do not store data |
| Indexes (INDEX) | be used for Improve query performance , It's equivalent to a book catalog |
| stored procedure (PROCEDURE) | Used to complete once Complete business processing , no return value , However, multiple values can be passed to the calling environment through outgoing parameters |
| Storage function (FUNCTION) | Used to complete once Specific calculations , Has a return value |
| trigger (TRIGGER) | Equivalent to one Event listener , When a specific event occurs in the database , Trigger is triggered , Complete the corresponding processing |
1.2 Reasons for using views
【 explain 】
On the one hand, views can help us Use part of the table Not all the tables , On the other hand, it can also aim at Different users To develop Different query views . such as , For a company's salesperson , We just want to show him Part of the data , And some Special data , For example, the purchase price , Will not be provided to him . Another example , Personnel compensation is a sensitive Field of , Then it is only open to people above a certain level , Others' query views are This field is not provided .
1.3 View understanding
【 a key 】
① View , Can be seen as a Virtual table , Itself is Don't store data Of . The essence of view , Can be seen as Store it Of select sentence
② The tables involved in the view are called Base watch
③ For views DML operation , Meeting influence To the data in the base table
④ Deleting the data in the view will not affect the data in the table
⑤ Application scenarios in the view : in the light of Small projects Not recommended . For large projects , Consider using views
⑥ Benefits of views : Simplify queries , Control data access
2. Create view
① stay CREATE VIEW Insert subquery in statement
CREATE [OR REPLACE] [ALGORITHM = {
UNDEFINED | MERGE | TEMPTABLE}] VIEW View name [( Field list )]
AS
Query statement
[WITH [CASCADED|LOCAL] CHECK OPTION]
Lite version ( After simplification )
CREATE VIEW View name
AS
Query statement
2.1 Create a single table view
Preparation before creating a view , Create databases and tables
CREATE DATABASE dbtest14;
use dbtest14;
CREATE TABLE emps
AS
SELECT *
FROM atguigudb.employees;
CREATE TABLE depts
AS
SELECT *
FROM atguigudb.departments;
Create a single table view
CREATE VIEW vu_emp1
AS
SELECT employee_id,last_name,salary
FROM emps;

The field is aliased after the view name
CREATE VIEW vu_emp3(id,name,salary)
AS
SELECT employee_id, last_name lname,salary
FROM emps
WHERE salary > 8000;

explain
① In fact, we are SQL Query statements encapsulation View VIEW, This will be based on SQL The result set of the statement forms a virtual table .
② When creating a view , Not after view name Specify the field list , The field list in the view defaults to and SELECT The list of fields in the statement is consistent . If SELECT Statement to the field Aliased , Then the field names in the view Same as alias .
2.2 Create a multi table union view
give an example :
① Multiple tables pass JOIN ON The way
CREATE VIEW vu_emp_dept
AS
SELECT e.employee_id, e.department_id, d.department_name
FROM emps e JOIN depts d
ON e.department_id = d.department_id;

② Use the view to format the data
We often need to output content in a certain format , For example, we want to output the employee name and the corresponding department name , The corresponding format is emp_name(department_name), You can use the view to complete the operation of data formatting :
CREATE VIEW vu_emp_dept2
AS
SELECT CONCAT(e.last_name,'(',d.department_name,')') emp_info
FROM emps e JOIN depts d
ON e.department_id = d.department_id;

③ Create a view based on the view
CREATE VIEW vu_emp4
AS
SELECT id,name
FROM vu_emp3;

3. Manage attempts
3.1 View view
The way 1:
View the table objects of the database 、 View objects
SHOW TABLES;

The way 2:
Look at the structure of the view
DESC / DESCRIBE View name ;
The way 3:
View the attribute information of the view
SHOW TABLE STATUS LIKE ' View name '\G
The way 4:
View the detailed definition information of the view
SHOW CREATE VIEW View name ;
3.2 Update data for view
Update view Syntax :
UPDATE View name
SET Update the content
WHERE Conditions
SELECT * FROM vu_emp1;
UPDATE vu_emp1
SET salary = 20000
WHERE employee_id = 102;


Two 、 Non updatable views
To make the view updatable , There must be... Between the rows in the view and the rows in the underlying base table one-on-one The relationship between . In addition, when the view definition is as follows , View does not support update operation :
① When defining the view, you specify “ALGORITHM = TEMPTABLE”, View will not support INSERT and DELETE operation ;
② The view does not contain Base watch All are defined as Not empty and not specified Default value column , View will not support INSERT operation ;
③ In defining the SELECT Used in the statement JOIN The joint query , View will not support INSERT and DELETE operation ;
④ In defining the SELECT The field list after the statement uses Mathematical expression or Subquery , View will not support INSERT, Nor does it support UPDATE Mathematical expressions are used 、 The field value of the subquery ;
⑤ In defining the SELECT Statement is used in the field list after the DISTINCT 、 Aggregate functions 、 GROUP BY 、 HAVING 、 UNION etc. , View will not support INSERT、UPDATE、DELETE;
⑥ In defining the SELECT The statement contains Subquery , The subquery refers to FROM The watch at the back , View will not support INSERT、UPDATE、DELETE;
⑦ The view definition is based on a Non updatable view ;
⑧ Constant View .
3.3 modify 、 Delete view
Modify the view
The way 1: Use CREATE OR REPLACE VIEW Clause to modify the view
CREATE OR REPLACE VIEW vu_emp1
AS
SELECT employee_id,last_name,salary,email
FROM emps;

The way 2:ALTER VIEW
ALTER VIEW vu_emp1
AS
SELECT employee_id,last_name,salary,email,hire_date
FROM emps;
Delete view
Be careful : Deleting a view just deletes the definition of the view , The data of the base table will not be deleted .
Use the syntax :
DROP VIEW IF EXISTS View name ;
explain :
View based a、b Created a new view c, If the view a Or view b Delete , Will cause the view c Your query failed . Such a view c Need to manually delete or modify , Otherwise, it will affect the use of .
3.4 View summary
1. It's easy to operate
Define frequently used query operations as View , It can make developers do not need to care about the data table corresponding to the view structure 、 Between tables Connections , There is no need to care about the relationship between data tables Business logic and Query criteria , And simply Operation view that will do , It greatly simplifies developers' understanding of Operation of database .
2. Reduce data redundancy
View with Actual data sheet Dissimilarity , It stores Query statement . therefore , In use , We will define the query statement of the view to Get the result set . And the view itself Don't store data , Do not occupy the resources of data storage , Reduce data redundancy .
3. Data security
MySQL The user's response to the data Access restrictions On the result set of some data , And these data Result set You can use views to implement . Users do not have to Direct inquiry or Operation data sheet . This can also be understood as the view has Isolation, . The view is equivalent to adding a layer between the user and the actual data table Virtual table . meanwhile ,MySQL Users' access to data can be restricted to some views according to their permissions , Users do not need to query the data table , The information in the data table can be obtained directly through the view . To a certain extent, this ensures that the data in the data table Security .
4. Adapt to flexible needs
When the requirements of the business system change , if necessary Change data sheet Structure , The workload is relatively large , You can use views to Reduce changes The amount of work . This method is often used in practical work .
5. Ability to decompose complex query logic
If there are complex Query logic , Then the problem can be decompose , Create multiple views get data , Then combine the created multiple views , Complete complex query logic . If we create a view based on the actual data table , that , If the actual data sheet Structural change , We need to update the relevant views in time Corresponding maintenance . especially Nested views ( Is to create a view based on the view ), Maintenance will become more complex , Poor readability , It can easily become a potential hidden danger of the system . Because the view is created SQL Queries may rename fields , It may also contain complex logic , These will increase the cost of maintenance .
边栏推荐
- JVM foundation > CMS garbage collector
- 【LeetCode】209. 长度最小的子数组
- 【LeetCode】5. Longest Palindromic Substring
- Zhengzhou University of light industry -- development and sharing of harmonyos pet health system
- Web3 principle and decentralization
- Introduction to Quaternion
- [recommended collection] easy to understand graphic network knowledge - Part 1
- Mysql concat_ws、concat函数使用
- 数字藏品的发展趋势!
- Avoid using asp Net core 3.0 to inject services for startup classes
猜你喜欢

Hostvars in ansible

80 lines of code to realize simple rxjs

MySQL case when then function use

ShardingSphere-proxy-5.0.0部署之分表实现(一)

Alcohol detector based on 51 single chip microcomputer
![[Part 8] semaphore source code analysis and application details [key points]](/img/e2/05c08435d60564aaa1172d2d574675.jpg)
[Part 8] semaphore source code analysis and application details [key points]

The development trend of digital collections!

ASP. Net core Middleware

iShot

iShot
随机推荐
【890. 查找和替换模式】
JVM Basics - > What are the thread shared areas in the JVM
JVM foundation > CMS garbage collector
Hostvars in ansible
The annual salary of 500000 is one line, and the annual salary of 1million is another line
2022 heavyweight: growth law - skillfully use digital marketing to break through enterprise difficulties
Coordinate transformation in pipelines
【LeetCode】69. Square root of X
Is it safe to open an account in flush? How to open an account online to buy stocks
DETR(Detection with Transformers) 学习笔记
The "fourteenth five year plan" development plan and panoramic strategic analysis report of China's information and innovation industry 2022 ~ 2028
数字藏品的发展趋势!
China embolic coil market trend report, technical innovation and market forecast
ASP. Net core Middleware
JVM foundation - > what is STW?
Sword finger offer series - 47 Maximum value of gifts
PHP删除二维数组中相同项的数据
The development trend of digital collections!
Shardingsphere-proxy-5.0.0 deployment table implementation (I)
Lua conditional statement