当前位置:网站首页>[MySQL] introduction, function, creation, view, deletion and modification of database view (with exercises)
[MySQL] introduction, function, creation, view, deletion and modification of database view (with exercises)
2022-07-04 06:32:00 【Xiaohuang Xiaohuang is no longer confused】
Personal home page : Huang Xiaohuang's blog home page
️ Stand by me : give the thumbs-up Collection Focus on
Maxim : Only one step at a time can we accept the so-called luckThis article is from the column :MySQL8.0 Learning notes
This article refers to the video :MySQL Database complete tutorial
Welcome to the support subscription column ️
List of articles
1 Introduction and function of view
Introduction to view :
- View view It's a virtual table , It's not real , Its The essence is the basis SQL Statement to get a dynamic data set , And name it , Users only need to use the view name to get the result set , And you can use it as a table .
- Only the definition of view is stored in the database , There is no data stored in view . The data still exists in the original data table .
- When using views to query data , The database system will take the corresponding data from the original table . therefore , The data in the view depends on the data in the original table . When the data of the table changes , The data in the view will also change .
The function of view :
- Simplify the code , We can encapsulate reused queries into views for reuse , Also can Make complex queries easy to understand ;
- More secure , such as , If there is a table with a lot of data , A lot of information doesn't want to be seen by others , Then you can use the view , Use different views for different users .
2 View creation
The syntax for creating a view is as follows :
create [or replace] [algorithm = {
undefined | merge | temptable}]
view view_name [(column_list)]
as select_statement
[with [cascaded | local] check option]
Parameter description :
- algorithm: Algorithm for view selection , Optional ;
- view_name: Name of the created view ;
- column_list: Specifies the noun for each attribute in the view , By default, it is the same as SELECT The properties of the query in the statement are the same ;
- select_statement: Represents a complete query statement , Import the query record into the view ;
- [with [cascaded | local] check option]: It means to ensure that the view is within the permission range when updating the view .
3 View modification
Modifying a view means modifying the definition of a table that already exists in the database . When some fields in the basic table change , You can modify the view to keep the consistency between the view and the basic table .
️ Grammar format :
alter view View name as select sentence ;
4 Update of view
Not all views can be updated . Can be in UPDATE、DELETE or INSERT And so on , To update the contents of the basic table . For updatable views , There must be a one-to-one relationship between the rows in the view and the rows in the basic table , If the view contains any of the following structures , The view is not updatable :
- Aggregate functions (SUM()、MIN()、MAX() etc. );
- DISTINCT;
- HAVING;
- UNION perhaps UNION ALL;
- Subqueries in the selection list ;
- JOIN;
- FROM Non updatable view in Clause ;
- WHERE Subquery in Clause , quote FROM Table in clause ;
- Use only literal values ( In this case , There are no basic tables to update ).
Be careful :
Although the data can be updated in the view , But there are many limitations . In general , It's best to use the view as a virtual table for querying data , Instead of updating data through views .
When a field existing in the view is modified in the real table , The view needs to be updated , Otherwise, the view will become invalid !
5 Rename and delete views
Rename view :
rename table View name to New view name ;
Delete view :
drop view if exists View name ;
When deleting a view , Only the definition of the view is deleted , It will not delete the data in the real table
If you want to delete multiple views at the same time , Then use the following syntax format :
drop view if exists View name 1, View name 2, View name 3...;
6 View exercises
6.1 Data preparation
When practicing, you can first create two basic tables for practice according to the following code :
create table college
(
cno int null,
cname varchar(20) null
);
create table student
(
sid int null,
name varchar(20) null,
gender varchar(20) null,
age int null,
birth date null,
address varchar(20) null,
score double null
);
The basic data of the two tables are shown in the figure below :
6.2 Query the name of the school with the highest average score
Combined with the knowledge learned before, you can Try subqueries and join queries To achieve , The reference codes are as follows :
SELECT cname
FROM (SELECT cname, rank() over (order by avg_score desc ) item
FROM (SELECT cname, avg(score) avg_score
FROM student
JOIN college ON sid = cno
GROUP BY cname) t) tt
WHERE item = 1;
In the above code , First the student And college The two tables are related , Treat the associated query as a sub table , And sort the average according to the sub table , The average number is 1 Has the highest average score , Then take this as a sub table for sub query , The school with the highest average score was found . The results are as follows :
Although this method can solve the problem , But it's relatively complicated , It's not easy to understand , To simplify the code , We can create each subquery as a view
View solution code :
-- 1 View one , Connect the two tables and calculate the average
CREATE VIEW t_view AS
SELECT cname, avg(score) avg_score
FROM student
JOIN college ON sid = cno
GROUP BY cname;
-- 2 View II , Use view 1 to sort and label the average scores
CREATE VIEW tt_view AS
SELECT cname, rank() over (order by avg_score desc ) item
FROM (t_view);
-- 3 Use view to query
SELECT cname
FROM (tt_view)
WHERE item = 1;
After creating the view , If you want to check the top three schools with average scores , It's a lot more convenient , The created view can be used directly !
Reference code and results :
SELECT cname
FROM (tt_view)
WHERE item = 1
OR item = 2
OR item = 3;
At the end
The above is the whole content of this article , The follow-up will continue Free update , If the article helps you , Please use your hands Point a praise + Focus on , Thank you very much ️ ️ ️ !
If there are questions , Welcome to the private letter or comment area !
Mutual encouragement :“ You make intermittent efforts and muddle through , It's all about clearing the previous efforts .”
边栏推荐
- [problem record] 03 connect to MySQL database prompt: 1040 too many connections
- Matlab remainder
- 树形dp
- 《ClickHouse原理解析与应用实践》读书笔记(4)
- C # symmetric encryption (AES encryption) ciphertext results generated each time, different ideas, code sharing
- Yiwen unlocks Huawei's new cloud skills - the whole process of aiot development [device access - ESP end-to-side data collection [mqtt]- real time data analysis] (step-by-step screenshot is more detai
- 云原生——上云必读之SSH篇(常用于远程登录云服务器)
- Tree DP
- Internet of things protocol ZigBee ZigBee module uses the concept of protocol stack
- Tsinghua University product: penalty gradient norm improves generalization of deep learning model
猜你喜欢
C realize Snake games
Learning multi-level structural information for small organ segmentation
Bicolor case
JS execution mechanism
Win10 clear quick access - leave no trace
Detailed explanation of common APIs for component and container containers: frame, panel, scrollpane
buuctf-pwn write-ups (8)
How to solve the component conflicts caused by scrollbars in GridView
buuctf-pwn write-ups (8)
Tree DP
随机推荐
27-31. Dependency transitivity, principle
The solution of win11 taskbar right click without Task Manager - add win11 taskbar right click function
Fast power (template)
Notes and notes
How to avoid JVM memory leakage?
4G wireless all network solar hydrological equipment power monitoring system bms110
剑指 Offer II 038. 每日温度
Arcpy uses the updatelayer function to change the symbol system of the layer
双色球案例
2022.7.3-----leetcode.556
Compound nonlinear feedback control (2)
Practical gadget instructions
Stc8h development (XII): I2C drive AT24C08, at24c32 series EEPROM storage
C language - Blue Bridge Cup - Snake filling
SQL join, left join, right join usage
2022.7.2-----leetcode.871
SQL injection SQL lab 11~22
R statistical mapping - random forest classification analysis and species abundance difference test combination diagram
Nexus 6p downgraded from 8.0 to 6.0+root
ADC voltage calculation of STM32 single chip microcomputer