当前位置:网站首页>[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 luck

This 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 ️
 Insert picture description here



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 :

  1. algorithm: Algorithm for view selection , Optional ;
  2. view_name: Name of the created view ;
  3. 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 ;
  4. select_statement: Represents a complete query statement , Import the query record into the view ;
  5. [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 :

  1. Aggregate functions (SUM()、MIN()、MAX() etc. );
  2. DISTINCT;
  3. HAVING;
  4. UNION perhaps UNION ALL;
  5. Subqueries in the selection list ;
  6. JOIN;
  7. FROM Non updatable view in Clause ;
  8. WHERE Subquery in Clause , quote FROM Table in clause ;
  9. 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 :
 Insert picture description here

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 :
 Insert picture description here

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;

 Insert picture description here


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 !
 Insert picture description here

Mutual encouragement :“ You make intermittent efforts and muddle through , It's all about clearing the previous efforts .”
 Insert picture description here

原网站

版权声明
本文为[Xiaohuang Xiaohuang is no longer confused]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/185/202207040629098113.html