search
HomeDatabaseMysql TutorialMySQL笔记之视图的使用详解_MySQL

bitsCN.com

什么是视图

视图是从一个或多个表中导出来的表,是一种虚拟存在的表。

视图就像一个窗口,通过这个窗口可以看到系统专门提供的数据。

这样,用户可以不用看到整个数据库中的数据,而之关心对自己有用的数据。

数据库中只存放了视图的定义,而没有存放视图中的数据,这些数据存放在原来的表中。

使用视图查询数据时,数据库系统会从原来的表中取出对应的数据。

视图中的数据依赖于原来表中的数据,一旦表中数据发生改变,显示在视图中的数据也会发生改变。

 

视图的作用

1.使操作简单化,可以对经常使用的查询定义一个视图,使用户不必为同样的查询操作指定条件

2.增加数据的安全性,通过视图,用户只能查询和修改指定的数据。

3.提高表的逻辑独立性,视图可以屏蔽原有表结构变化带来的影响。

 

总而言之,使用视图的大部分情况是为了保障数据安全性,提高查询效率

 

参考表:

创建视图的语法

CREATE [ALGORITHM]={UNDEFINED|MERGE|TEMPTABLE}]
       VIEW 视图名 [(属性清单)]
       AS SELECT 语句
       [WITH [CASCADED|LOCAL] CHECK OPTION];

ALGORITHM表示视图选择的算法(可选参数)

      UNDEFINED:MySQL将自动选择所要使用的算法
      MERGE:将视图的语句与视图定义合并起来,使得视图定义的某一部分取代语句的对应部分
      TEMPTABLE:将视图的结果存入临时表,然后使用临时表执行语句

视图名表示要创建的视图的名称

属性清单表示视图中的列名,默认与SELECT查询结果中的列名相同(可选参数)

WITH CHECK OPTION表示更新视图时要保证在该试图的权限范围之内(可选参数)

      CASCADED:更新视图时要满足所有相关视图和表的条件
      LOCAL:更新视图时,要满足该视图本身定义的条件即可

 

tips:创建试图时最好加上WITH CASCADED CHECK OPTION参数,这种方式比较严格

     可以保证数据的安全性


视图操作
在单表上创建视图

mysql> CREATE VIEW work_view(ID,NAME,ADDR) AS SELECT id,name,address FROM work; 
Query OK, 0 rows affected (0.05 sec)

此处work_view为视图名,后面括号内的参数代表视图中的列

AS表示将后面SELECT 语句中的查询结果赋给前面的视图中

在多表上创建视图

mysql> CREATE ALGORITHM=MERGE VIEW work_view2(ID,NAME,SALARY)
    -> AS SELECT work.id,name,salary FROM work,salary
    -> WHERE work.id=salary.id
    -> WITH LOCAL CHECK OPTION;
Query OK, 0 rows affected (0.02 sec)

在多表中创建视图需要两表有指定联系,如上面的work.id=salary.id


SELECT查询视图

mysql> SELECT * FROM work_view;
+----+--------+--------+
| ID | NAME   | ADDR   |
+----+--------+--------+
|  1 | 张三   | 北京   |
|  2 | 李四   | 上海   |
|  3 | 王五   | 湖南   |
|  4 | 赵六   | 重庆   |
+----+--------+--------+
 rows in set (0.00 sec)

此处的SELECT语句用法和其他表中的用法一样

别忘了,视图也是一张表,只不过它是虚拟的


DESCRIBE查看视图基本信息

mysql> DESCRIBE work_view;
+-------+-------------+------+-----+---------+-------+
| Field | Type        | Null | Key | Default | Extra |
+-------+-------------+------+-----+---------+-------+
| ID    | int(10)     | NO   |     | NULL    |       |
| NAME  | varchar(20) | NO   |     | NULL    |       |
| ADDR  | varchar(50) | YES  |     | NULL    |       |
+-------+-------------+------+-----+---------+-------+
 rows in set (0.00 sec)

与以往一样,此处的DESCRIBE可以简写为DESC


SHOW TABLE STATUS查看视图基本信息

mysql> SHOW TABLE STATUS LIKE 'work_view'/G
*************************** 1. row ***************************
           Name: work_view
         Engine: NULL
        Version: NULL
     Row_format: NULL
           Rows: NULL
 Avg_row_length: NULL
    Data_length: NULL
Max_data_length: NULL
   Index_length: NULL
      Data_free: NULL
 Auto_increment: NULL
    Create_time: NULL
    Update_time: NULL
     Check_time: NULL
      Collation: NULL
       Checksum: NULL
 Create_options: NULL
        Comment: VIEW
 row in set (0.00 sec)

此处大部分信息显示为NULL,更加说明了视图只是一张虚拟表

如果使用SHOW TABLE STATUS查看一张真实表,结果就不会如此

SHOW CREATE VIEW查看视图详细信息

mysql> SHOW CREATE VIEW work_view/G
*************************** 1. row ***************************
                View: work_view
         Create View: CREATE ALGORITHM=UNDEFINED DEFINER=`root`@`localhost` SQL SECURITY DEFINER VIEW `work_view` AS select `work`.`id` AS `ID`,`work`.`name` AS `NAME`,`work`.`address` AS `ADDR` from `work`
character_set_client: utf8
collation_connection: utf8_general_ci
 row in set (0.00 sec)

尼玛好复杂,这里包含了视图的各个属性

在views表中查看视图详细信息

mysql> SELECT * FROM information_schema.views/G
*************************** 1. row ***************************
       TABLE_CATALOG: def
        TABLE_SCHEMA: person
          TABLE_NAME: work_view
     VIEW_DEFINITION: select `person`.`work`.`id` AS `ID`,`person`.`work`.`name` AS `NAME`,`person`.`work`.`address` AS `ADDR` from `person`.`work`
        CHECK_OPTION: NONE
        IS_UPDATABLE: YES
             DEFINER: root@localhost
       SECURITY_TYPE: DEFINER
CHARACTER_SET_CLIENT: utf8
COLLATION_CONNECTION: utf8_general_ci
*************************** 2. row ***************************
       TABLE_CATALOG: def
        TABLE_SCHEMA: person
          TABLE_NAME: work_view2

information_schema.views表内包含了所有的视图定义信息

不过,通常使用SHOW CREATE VIEW 更加方便

这里信息太长,没有完全列举……


修改视图

修改视图是指修改数据库中已存在的表的定义,当基本表的某些字段发生改变时,可以通过修改视图来保持视图和基本表之间一致
CREATE OR REPLACE VIEW语句修改视图

mysql> CREATE OR REPLACE ALGORITHM=TEMPTABLE
    -> VIEW work_view(ID,NAME)
    -> AS SELECT id,name FROM work;
Query OK, 0 rows affected (0.03 sec)

话说,CREATE OR REPLACE语句非常灵活

在视图存在的情况下可对视图进行修改,视图不在的情况下可创建视图

其基本用法和CREATE VIEW 几乎一致


ALTER语句修改视图

mysql> ALTER VIEW work_view2(NAME,SALARY,ADDR)
    -> AS SELECT name,salary,address FROM work,salary
    -> WHERE work.id=salary.id;
Query OK, 0 rows affected (0.03 sec)

我这把名字、工资和地址当做字段修改了视图

如果是真实的话,对小偷来说极为方便

更新视图

更新视图是指通过视图来插入、更新和删除表中的数据,以为视图是一个虚拟表,其中木有数据

通过视图更新时,都是转换到基本表来更新

mysql> UPDATE work_view2 SET SALARY=5899.00 WHERE NAME='张三';
Query OK, 1 row affected (0.03 sec)
Rows matched: 1  Changed: 1  Warnings: 0

此处语句等价于

mysql> UPDATE salary SET salary=5899.00 WHERE id=1;

tips:视图中虽然可以更新数据,但是有很多限制

   一般情况下,最好将视图作为查询数据的虚拟表,而不要通过视图更新数据


删除视图

删除视图是指删除数据库中已存在的视图,删除视图时,只能删除视图的定义,不会删除数据

mysql> DROP VIEW IF EXISTS work_view;
Query OK, 0 rows affected (0.00 sec)

mysql> DROP VIEW work_view2;
Query OK, 0 rows affected (0.01 sec)

这里的IF EXIST参数用来判断视图是否存在,也可以不写

bitsCN.com
Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Explain the InnoDB Buffer Pool and its importance for performance.Explain the InnoDB Buffer Pool and its importance for performance.Apr 19, 2025 am 12:24 AM

InnoDBBufferPool reduces disk I/O by caching data and indexing pages, improving database performance. Its working principle includes: 1. Data reading: Read data from BufferPool; 2. Data writing: After modifying the data, write to BufferPool and refresh it to disk regularly; 3. Cache management: Use the LRU algorithm to manage cache pages; 4. Reading mechanism: Load adjacent data pages in advance. By sizing the BufferPool and using multiple instances, database performance can be optimized.

MySQL vs. Other Programming Languages: A ComparisonMySQL vs. Other Programming Languages: A ComparisonApr 19, 2025 am 12:22 AM

Compared with other programming languages, MySQL is mainly used to store and manage data, while other languages ​​such as Python, Java, and C are used for logical processing and application development. MySQL is known for its high performance, scalability and cross-platform support, suitable for data management needs, while other languages ​​have advantages in their respective fields such as data analytics, enterprise applications, and system programming.

Learning MySQL: A Step-by-Step Guide for New UsersLearning MySQL: A Step-by-Step Guide for New UsersApr 19, 2025 am 12:19 AM

MySQL is worth learning because it is a powerful open source database management system suitable for data storage, management and analysis. 1) MySQL is a relational database that uses SQL to operate data and is suitable for structured data management. 2) The SQL language is the key to interacting with MySQL and supports CRUD operations. 3) The working principle of MySQL includes client/server architecture, storage engine and query optimizer. 4) Basic usage includes creating databases and tables, and advanced usage involves joining tables using JOIN. 5) Common errors include syntax errors and permission issues, and debugging skills include checking syntax and using EXPLAIN commands. 6) Performance optimization involves the use of indexes, optimization of SQL statements and regular maintenance of databases.

MySQL: Essential Skills for Beginners to MasterMySQL: Essential Skills for Beginners to MasterApr 18, 2025 am 12:24 AM

MySQL is suitable for beginners to learn database skills. 1. Install MySQL server and client tools. 2. Understand basic SQL queries, such as SELECT. 3. Master data operations: create tables, insert, update, and delete data. 4. Learn advanced skills: subquery and window functions. 5. Debugging and optimization: Check syntax, use indexes, avoid SELECT*, and use LIMIT.

MySQL: Structured Data and Relational DatabasesMySQL: Structured Data and Relational DatabasesApr 18, 2025 am 12:22 AM

MySQL efficiently manages structured data through table structure and SQL query, and implements inter-table relationships through foreign keys. 1. Define the data format and type when creating a table. 2. Use foreign keys to establish relationships between tables. 3. Improve performance through indexing and query optimization. 4. Regularly backup and monitor databases to ensure data security and performance optimization.

MySQL: Key Features and Capabilities ExplainedMySQL: Key Features and Capabilities ExplainedApr 18, 2025 am 12:17 AM

MySQL is an open source relational database management system that is widely used in Web development. Its key features include: 1. Supports multiple storage engines, such as InnoDB and MyISAM, suitable for different scenarios; 2. Provides master-slave replication functions to facilitate load balancing and data backup; 3. Improve query efficiency through query optimization and index use.

The Purpose of SQL: Interacting with MySQL DatabasesThe Purpose of SQL: Interacting with MySQL DatabasesApr 18, 2025 am 12:12 AM

SQL is used to interact with MySQL database to realize data addition, deletion, modification, inspection and database design. 1) SQL performs data operations through SELECT, INSERT, UPDATE, DELETE statements; 2) Use CREATE, ALTER, DROP statements for database design and management; 3) Complex queries and data analysis are implemented through SQL to improve business decision-making efficiency.

MySQL for Beginners: Getting Started with Database ManagementMySQL for Beginners: Getting Started with Database ManagementApr 18, 2025 am 12:10 AM

The basic operations of MySQL include creating databases, tables, and using SQL to perform CRUD operations on data. 1. Create a database: CREATEDATABASEmy_first_db; 2. Create a table: CREATETABLEbooks(idINTAUTO_INCREMENTPRIMARYKEY, titleVARCHAR(100)NOTNULL, authorVARCHAR(100)NOTNULL, published_yearINT); 3. Insert data: INSERTINTObooks(title, author, published_year)VA

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.