当前位置:网站首页>[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 .”
边栏推荐
- JSON Web Token----JWT和傳統session登錄認證對比
- Abap:ooalv realizes the function of adding, deleting, modifying and checking
- InputStream/OutputStream(文件的输入输出)
- Nexus 6p从8.0降级6.0+root
- STC8H开发(十二): I2C驱动AT24C08,AT24C32系列EEPROM存储
- The width of the picture in rich text used by wechat applet exceeds the problem
- Invalid bound statement (not found): com. example. mapper. TblUserRecordMapper. login
- How does apscheduler set tasks not to be concurrent (that is, execute the next task after the first one)?
- 24 magicaccessorimpl can access the debugging of all methods
- High performance parallel programming and optimization | lesson 02 homework at home
猜你喜欢
Native Cloud - SSH articles must be read on Cloud (used for Remote Login to Cloud Server)
Detectron:训练自己的数据集——将自己的数据格式转换成COCO格式
Inputstream/outputstream (input and output of file)
A little understanding of GSLB (global server load balance) technology
17-18. Dependency scope and life cycle plug-ins
C语言练习题(递归)
what the fuck! If you can't grab it, write it yourself. Use code to realize a Bing Dwen Dwen. It's so beautiful ~!
Common usage of time library
MySQL learning notes 3 - JDBC
R statistical mapping - random forest classification analysis and species abundance difference test combination diagram
随机推荐
STC8H开发(十二): I2C驱动AT24C08,AT24C32系列EEPROM存储
After the festival, a large number of people change careers. Is it still time to be 30? Listen to the experience of the past people
Invalid revision: 3.18.1-g262b901-dirty
JS get the attribute values nested in the object
《ClickHouse原理解析与应用实践》读书笔记(4)
C语言中的排序,实现从小到大的数字排序法
Json Web token - jwt vs. Traditional session login Authentication
198. House raiding
8. Factory method
C实现贪吃蛇小游戏
MySQL installation and configuration
740. Delete and get points
ADC voltage calculation of STM32 single chip microcomputer
How to use multithreading to export excel under massive data? Source code attached!
How to solve the component conflicts caused by scrollbars in GridView
Native Cloud - SSH articles must be read on Cloud (used for Remote Login to Cloud Server)
Fast power (template)
Layoutmanager layout manager: flowlayout, borderlayout, GridLayout, gridbaglayout, CardLayout, BoxLayout
R statistical mapping - random forest classification analysis and species abundance difference test combination diagram
Tree DP