当前位置:网站首页>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 .
边栏推荐
- [Part 7] source code analysis and application details of cyclicbarrier [key]
- Plusieurs camarades de classe de Tsinghua sont partis...
- C language: how to give an alias to a global variable?
- 细数攻防演练中十大关键防守点
- 3.5 setup and teardown of test classes
- Mysql concat_ws、concat函数使用
- MYSQL 行转列、列转行、多列转一行、一行转多列
- 【LeetCode】300. Longest ascending subsequence
- Analysis report on production and marketing demand and investment forecast of China's Melamine Industry from 2022 to 2028
- Generate the chrysanthemum code of the applet (generate the chrysanthemum code, change the middle logo, change the image size, and add text)
猜你喜欢

C#读取word中表格数据

数字藏品的发展趋势!

C # reading table data in word

Colab tutorial (super detailed version) and colab pro/colab pro+ usage evaluation

Insight into China's smart medical industry in 2022

Use js to listen for Keydown event

年薪50万是一条线,年薪100万又是一条线…...

Colab tutorial (super detailed version) and colab pro/colab pro+ usage evaluation

OpenCV源代码编译

JVM foundation > G1 garbage collector
随机推荐
PHP deletes data of the same item in a two-dimensional array
Introduction to Quaternion
China embolic coil market trend report, technical innovation and market forecast
lua 日期时间
管线中的坐标变换
The development trend of digital collections!
Lua date time
MYSQL 行转列、列转行、多列转一行、一行转多列
Analysis report on the 14th five year development plan and operation mode of China's hazardous waste treatment industry from 2022 to 2028
PyTorch常用参数初始化方法:【均匀分布、正态(高斯)分布、Xavier、kaiming、正交矩阵、稀疏矩阵、常数、单位矩阵、零填充】
【LeetCode】5. Longest Palindromic Substring
lua 条件语句
JVM Basics - > What are the JVM parameters?
[leetcode] sword finger offer II 020 Number of palindrome substrings
Go time format assignment
JVM foundation > CMS garbage collector
Anti aliasing / anti aliasing Technology
QT quick 3D learning: use mouse and keyboard to control node position and direction
USB mechanical keyboard changed to Bluetooth Keyboard
QT quick 3D learning: mouse picking up objects