当前位置:网站首页>MySQL concept - View
MySQL concept - View
2022-06-24 06:34:00 【User 1348170】
One . brief introduction
View (view) It's a virtual existence table , It's a logical table , It doesn't contain data in itself . As a select Statement stored in the data dictionary . Through view , Some data of the base table can be displayed ; View data comes from tables used in queries that define views , Use view dynamic generation .
Base watch : The table used to create the view is called the base table base table
Two 、 advantage
- Simple : Users of views do not need to care about the structure of the corresponding tables 、 Association and screening criteria , It is already the result set of filtered composite conditions for users .
- Security : Users of views can only access the result set they are allowed to query , Permission management of a table cannot be limited to a row or a column , But it can be realized simply by view .
- Data independence : Once the structure of the view is determined , It can shield the influence of table structure change on users , Adding columns to the source table has no effect on the view ; Source table change column name , Can be solved by modifying the view , No impact on visitors .
To make a long story short , Most of the views are used for Data security , Improve query efficiency .
3、 ... and 、 Use
Create view
CREATE [OR REPLACE] [ALGORITHM = {UNDEFINED | MERGE | TEMPTABLE}] VIEW view_name [(column_list)] AS select_statement [WITH [CASCADED | LOCAL] CHECK OPTION]1)OR REPLACE: Represents replacing an existing view
2)ALGORITHM: Represents the view selection algorithm , The default algorithm is UNDEFINED( Undefined ):MySQL Automatically select the algorithm to use ;merge Merge ;temptable A temporary table
3)select_statement: Express select sentence
4)[WITH [CASCADED | LOCAL] CHECK OPTION]: It means that the view is guaranteed to be within the permission range of the view when it is updated
cascade Is the default value , Indicates when the view is updated , To meet the relevant conditions of views and tables
local Indicates when the view is updated , To meet a condition defined by the view
TIPS: Recommended WHIT [CASCADED|LOCAL] CHECK OPTION Options , It can guarantee the security of data
The basic format : create view < View name >[(column_list)] as select sentence with check option;
1、 stay Single table Create views on
mysql> create view v_F_players( Number , name , Gender , Telephone ) -> as -> select PLAYERNO,NAME,SEX,PHONENO from PLAYERS -> where SEX='F' -> with check option;Query OK, 0 rows affected (0.00 sec)mysql> desc v_F_players;+--------+----------+------+-----+---------+-------+| Field | Type | Null | Key | Default | Extra |+--------+----------+------+-----+---------+-------+| Number | int(11) | NO | | NULL | || name | char(15) | NO | | NULL | || Gender | char(1) | NO | | NULL | || Telephone | char(13) | YES | | NULL | |+--------+----------+------+-----+---------+-------+4 rows in set (0.00 sec)mysql> select * from v_F_players;+--------+-----------+--------+------------+| Number | name | Gender | Telephone |+--------+-----------+--------+------------+| 8 | Newcastle | F | 070-458458 || 27 | Collins | F | 079-234857 || 28 | Collins | F | 010-659599 || 104 | Moorman | F | 079-987571 || 112 | Bailey | F | 010-548745 |+--------+-----------+--------+------------+5 rows in set (0.02 sec)
2、 stay Multiple tables Create views on
mysql> create view v_match -> as -> select a.PLAYERNO,a.NAME,MATCHNO,WON,LOST,c.TEAMNO,c.DIVISION -> from -> PLAYERS a,MATCHES b,TEAMS c -> where a.PLAYERNO=b.PLAYERNO and b.TEAMNO=c.TEAMNO;Query OK, 0 rows affected (0.03 sec)mysql> select * from v_match;+----------+-----------+---------+-----+------+--------+----------+| PLAYERNO | NAME | MATCHNO | WON | LOST | TEAMNO | DIVISION |+----------+-----------+---------+-----+------+--------+----------+| 6 | Parmenter | 1 | 3 | 1 | 1 | first || 44 | Baker | 4 | 3 | 2 | 1 | first || 83 | Hope | 5 | 0 | 3 | 1 | first || 112 | Bailey | 12 | 1 | 3 | 2 | second || 8 | Newcastle | 13 | 0 | 3 | 2 | second |+----------+-----------+---------+-----+------+--------+----------+5 rows in set (0.04 sec)
- Views filter out data we don't need , Replace the relevant column names with our custom ones . View as a provider , No matter how complex the table structure and table name of the base table are .
- If the column name of the view is not explicitly specified when creating the view , Then the column name is the same as the... That defines the view select The column names in the clause are exactly the same ;
- If you explicitly specify the column name of the view, it will be based on the specified column name . Be careful : Displays the specified view column name , The number of columns after the view name must match select Number of columns in clause .
View view
1、 Use show create view Statement to view view information
mysql> show create view v_F_players\G;*************************** 1. row *************************** View: v_F_players Create View: CREATE ALGORITHM=UNDEFINED DEFINER=`root`@`localhost` SQL SECURITY DEFINER VIEW `v_F_players` AS select `PLAYERS`.`PLAYERNO` AS ` Number `,`PLAYERS`.`NAME` AS ` name `,`PLAYERS`.`SEX` AS ` Gender `,`PLAYERS`.`PHONENO` AS ` Telephone ` from `PLAYERS` where (`PLAYERS`.`SEX` = 'F') WITH CASCADED CHECK OPTIONcharacter_set_client: utf8collation_connection: utf8_general_ci1 row in set (0.00 sec)
2、 Once the view is created , It can be used like an ordinary table , Views are mainly used to query mysql> select * from view_name; 3、 Information about the view is recorded in the information_schema In the database views In the table
mysql> select * from information_schema.views -> where TABLE_NAME='v_F_players'\G;*************************** 1. row *************************** TABLE_CATALOG: def TABLE_SCHEMA: TENNIS TABLE_NAME: v_F_players VIEW_DEFINITION: select `TENNIS`.`PLAYERS`.`PLAYERNO` AS ` Number `,`TENNIS`.`PLAYERS`.`NAME` AS ` name `,`TENNIS`.`PLAYERS`.`SEX` AS ` Gender `,`TENNIS`.`PLAYERS`.`PHONENO` AS ` Telephone ` from `TENNIS`.`PLAYERS` where (`TENNIS`.`PLAYERS`.`SEX` = 'F') CHECK_OPTION: CASCADED IS_UPDATABLE: YES DEFINER: [email protected] SECURITY_TYPE: DEFINERCHARACTER_SET_CLIENT: utf8COLLATION_CONNECTION: utf8_general_ci1 row in set (0.00 sec)
View changes
1、CREATE OR REPLACE VIEW Statement modify view The basic format : create or replace view view_name as select sentence ; The view can be modified if it exists , You can create a view when the view is not present 2、ALTER Statement modify view
ALTER [ALGORITHM = {UNDEFINED | MERGE | TEMPTABLE}] [DEFINER = { user | CURRENT_USER }] [SQL SECURITY { DEFINER | INVOKER }]VIEW view_name [(column_list)]AS select_statement [WITH [CASCADED | LOCAL] CHECK OPTION]Be careful : Modifying a view means modifying the definition of a table that already exists in the database , When some fields of the base table change , You can modify the view to keep it consistent with the basic table
3、DML Action update view Because the view itself has no data , So for the view dml Operations are ultimately reflected in the base table
mysql> create view v_student as select * from student;mysql> select * from v_student;+--------+--------+------+| Student number | name | sex |+--------+--------+------+| 1 | Zhang San | M || 2 | Li Si | F || 5 | Wang Wu | NULL |+--------+--------+------+mysql> update v_student set name=' Qian Liu ' where Student number ='1';mysql> select * from student;+--------+--------+------+| Student number | name | sex |+--------+--------+------+| 1 | Qian Liu | M || 2 | Li Si | F || 5 | Wang Wu | NULL |+--------+--------+------+
Of course , View's DML operation , Not all views can do DML operation .
There is one of the following , View cannot be done DML operation :
①select Clause contains distinct
②select Clause contains group functions
③select The statement contains group by Clause
④select The statement contains order by Clause
⑤select The statement contains union 、union all Wait for the set operator
⑥where Clause contains related subqueries
⑦from Clause contains multiple tables
⑧ If there are calculated columns in the view , Can't update
⑨ If a column with non NULL constraint in the base table does not appear in the view definition , You can't do insert operation 4、drop Delete view
To delete a view is to delete a view that already exists in the database , When deleting a view , You can only delete the definition of a view , Data will not be deleted , That is to say, do not move the base table :
DROP VIEW [IF EXISTS] view_name [, view_name] ...
mysql> drop view v_student;
If the view does not exist , Throw an exception ; Use IF EXISTS Option so that no exception is thrown when deleting a view that does not exist .
Use WITH CHECK OPTION constraint
For can execute DML View of operations , When defining, you can bring WITH CHECK OPTION constraint effect : What's done to the view DML Results of operation , You cannot violate the view WHERE The limitation of conditions . Example : Create view , contain 1960 All the players born before ( veteran )
mysql> create view v_veterans -> as -> select * from PLAYERS -> where birth_date < '1960-01-01' -> with check option;Query OK, 0 rows affected (0.01 sec)mysql> select * from v_veterans;+----------+---------+----------+------------+-----+--------+----------------+---------+----------+-----------+------------+----------+| PLAYERNO | NAME | INITIALS | BIRTH_DATE | SEX | JOINED | STREET | HOUSENO | POSTCODE | TOWN | PHONENO | LEAGUENO |+----------+---------+----------+------------+-----+--------+----------------+---------+----------+-----------+------------+----------+| 2 | Everett | R | 1948-09-01 | M | 1975 | Stoney Road | 43 | 3575NH | Stratford | 070-237893 | 2411 || 39 | Bishop | D | 1956-10-29 | M | 1980 | Eaton Square | 78 | 9629CD | Stratford | 070-393435 | NULL || 83 | Hope | PK | 1956-11-11 | M | 1982 | Magdalene Road | 16A | 1812UP | Stratford | 070-353548 | 1608 |+----------+---------+----------+------------+-----+--------+----------------+---------+----------+-----------+------------+----------+3 rows in set (0.02 sec)
here , Use update Make changes to the view :
mysql> update v_veterans -> set BIRTH_DATE='1970-09-01' -> where PLAYERNO=39;ERROR 1369 (HY000): CHECK OPTION failed 'TENNIS.v_veterans'
Because it violates the... In the view WHERE birth_date < ‘1960-01-01’ Clause , So throw an exception ; utilize with check option Constraints , Ensure that the updated view is within the permissions of the view . Nested views : A view defined above another view
mysql> create view v_ear_veterans -> as -> select * from v_veterans -> where JOINED < 1980;
Use WITH CHECK OPTION When restrained ,( If no option is specified, the default is CASCADED) have access to CASCADED perhaps LOCAL Option specifies the extent of the check : ①WITH CASCADED CHECK OPTION: Check all views
for example : Nested views and their underlying views
②WITH LOCAL CHECK OPTION: Check only the view itself to be updated
Do not check the underlying view for nested views
Other options when defining views
CREATE [OR REPLACE] [ALGORITHM = {UNDEFINED | MERGE | TEMPTABLE}] [DEFINER = { user | CURRENT_USER }] [SQL SECURITY { DEFINER | INVOKER }]VIEW view_name [(column_list)] AS select_statement [WITH [CASCADED | LOCAL] CHECK OPTION]1、ALGORITHM Options : Select the process that defines the view select The method used in the statement
①UNDEFINED:MySQL The algorithm to be used will be automatically selected
②MERGE: Merge the statement of the view with the view definition , Make a part of the view definition replace the corresponding part of the statement
③TEMPTABLE: Store the results of the view in a temporary table , Then use the temporary table to execute the statement
default ALGORITHM Option is equivalent to ALGORITHM = UNDEFINED
2、DEFINER Options : Point out who is the creator or definer of the view
①definer= ‘ user name ‘@’ Log on to the host ’
② If you do not specify this option , The user who creates the view is the definer , Specify keywords CURRENT_USER( The current user ) The effect is the same as not specifying this option
3、SQL SECURITY Options : To query a view , First, you must have access to the view select jurisdiction .
however , If the same user doesn't have any information about the table accessed by the view select jurisdiction , What then ?
SQL SECURITY Option determines the result of execution :
①SQL SECURITY DEFINER: Definition ( establish ) The user of the view must have access to the table that the view accesses select jurisdiction , That is, when other users access the table in the future, they will act as the definer , Other users do not have access rights at this time .
②SQL SECURITY INVOKER: The user accessing the view must have access to the table accessed by the view select jurisdiction .
default SQL SECURITY Option is equivalent to SQL SECURITY DEFINER
Summary of view permissions :
Use root User defined view ( The first one is recommended ):u1、u2
1)u1 Define a view as a definer ,u1 The base table has select jurisdiction ,u2 Have access to the view :u2 It is accessed as the definer, and the contents of the base table can be queried ;
2)u1 Define a view as a definer ,u1 There is no effect on the base table select jurisdiction ,u2 Have access to the view ,u2 The base table has select jurisdiction :u2 The view is accessed as the caller , At this point, the caller is u2, You can query the contents of the base table .
边栏推荐
- How fast? Good province!
- Network Overview
- Domain name, resolution, SSL certificate FAQ
- SAP hum unbinds Hu from delivery order
- Rhel8 series update image Yum source is Tencent cloud Yum source
- Micro build low code supports Excel to import data source
- Analysis of official template of wechat personnel recruitment management system (III)
- Spirit information development log (1)
- Kangaroo cloud: the overall architecture and key technical points of building a real-time computing platform based on Flink
- WordPress applet build applet from zero to one [server configuration]
猜你喜欢

基于三维GIS系统的智慧水库管理应用
![[fault announcement] one stored procedure brings down the entire database](/img/7c/e5adda73a077fe4b8f04b59d1e0e1e.jpg)
[fault announcement] one stored procedure brings down the entire database

The product layout is strengthened, the transformation of digital intelligence is accelerated, and FAW Toyota has hit 2022million annual sales

Enter the software test pit!!! Software testing tools commonly used by software testers software recommendations
Oracle case: ohasd crash on AIX

ServiceStack. Source code analysis of redis (connection and connection pool)

Technology is a double-edged sword, which needs to be well kept

解读AI机器人产业发展的顶层设计

Manual for automatic testing and learning of anti stepping pits, one for each tester

创客教育给教师发展带来的挑战
随机推荐
解读AI机器人产业发展的顶层设计
What are the categories of edge computing devices
Semantic web, semantic web, linked data and knowledge map
How to open a hidden file
Fault analysis | using --force to batch import data leads to partial data loss
How to give full play to the advantages of Internet of things by edge computing intelligent gateway
5 minutes, online from 0 to 1!
Multi objective Optimization Practice Based on esmm model -- shopping mall
"Adobe international certification" in the design industry, why can't big but big designs have good results?
Royal treasure: an analysis of SQL algebra optimization
Network Overview
Manual for automatic testing and learning of anti stepping pits, one for each tester
In Tencent, my trial period summary
WordPress pill applet build applet from zero to one [applet registration configuration]
Easynvr is optimized when a large number of videos are not online or unstable due to streaming failure
MySQL forgets root password cracking root password cracking all user passwords, shell script
Intranet environment request Tencent cloud 3.0 API details
Tencent security release data security compliance capability map
DHCP server setup
Analysis and treatment of easydss flash back caused by system time