Home Database Mysql Tutorial Basic operations of MySQL views (5)_MySQL

Basic operations of MySQL views (5)_MySQL

Sep 09, 2016 am 08:13 AM
mysql view

1. Why use views:
In order to improve the reusability of complex SQL statements and the security of table operations (for example, the salary field does not want to be displayed to everyone who can view the query results), MySQL provides view features. The so-called view is essentially a virtual table whose content is similar to a real table and contains a series of named column and row data. However, views do not exist as stored data values ​​in the database. The row and column data come from the base table referenced by the query of the custom view and are dynamically generated when the view is used.
The view has the following characteristics;
​​ 1. The columns of the view can come from different tables, which is a new relationship established in the abstract and logical sense of the table.
​ ​ 2. A view is a table (virtual table) generated from a basic table (real table).
​ 3. The creation and deletion of views does not affect the basic tables.
​​ 4. Updates to view content (addition, deletion, and modification) directly affect the basic table.
5. When the view comes from multiple base tables, adding and deleting data is not allowed.

2. Create a view:
When creating a view, first make sure you have the CREATE VIEW permissions, and also make sure you have the corresponding permissions on the table referenced by the created view.
2.1 The syntax form of creating a view:
Although a view can be regarded as a virtual table, it does not exist physically, that is, the database management system does not have a special location to store data for the view. According to the concept of view, it is found that the data comes from the query statement, so the syntax for creating a view is:

CREATE VIEW view_name AS query statement
//Note: Just like creating a table, the view name cannot be the same as the table name or other view names. The function of the view is actually to encapsulate complex query statements.

Example:

use zhaojd_test;  //选择一个自己创建的库
create table t_product( //创建表
  id int primary key,
  pname varchar(20),
  price decimal(8,2)
); 
insert into t_product values(1,'apple',6.5); //向表中插入数据
insert into t_product values(2,'orange',3); //向表中插入数据
create view view_product as select id,name from t_product; //创建视图
select * from view_product;
Copy after login

The result is:
+------+--------+
| id | name |
+------+--------+
| 1 | apple |
| 2 | orange |
+------+--------+
//In fact, when creating the view, what is actually written in the code is a table query statement, but the query statement is encapsulated and given a new name so that it can be reused.
//Furthermore, in terms of security, you can hide some fields you don't want to see, such as the price field here.
//Note: In the naming convention of SQL statements, views are generally named in the style of view_xxx or v_xxx. The query statement of the view is the same as the query statement of the table.

2.2 Create various views:
Since the function of the view actually encapsulates the query statement in real time, can any form of query statement be encapsulated in the view?

2.2.1 Encapsulate the view that implements query constant statements (constant view):

Example:

mysql> create view view_test1 as select 3.1415926;
Query OK, 0 rows affected (0.07 sec)
mysql> select * from view_test1;
+-----------+
| 3.1415926 |
+-----------+
| 3.1415926 |
+-----------+
1 row in set (0.00 sec)
Copy after login

2.2.2 Encapsulate views that use aggregate functions (SUM, MIN, MAX, COUNT, etc.) query statements:

Example:
First prepare the two tables and their initialization data that need to be used;

CREATE TABLE t_group(
  id INT PRIMARY KEY AUTO_INCREMENT,
  NAME VARCHAR(20)
);
CREATE TABLE t_student(
  id INT PRIMARY KEY AUTO_INCREMENT,
  NAME VARCHAR(20),
  sex CHAR(1),
  group_id INT,
  FOREIGN KEY (group_id) REFERENCES t_group (id)
);
//t_group表中插入数据
INSERT INTO t_group (NAME) VALUES('group_1');
INSERT INTO t_group (NAME) VALUES('group_2');
INSERT INTO t_group (NAME) VALUES('group_3');
INSERT INTO t_group (NAME) VALUES('group_4');
INSERT INTO t_group (NAME) VALUES('group_5');
//t_student表中插入数据
INSERT INTO t_student (NAME,sex,group_id) VALUES('zjd_1','M',1);
INSERT INTO t_student (NAME,sex,group_id) VALUES('zjd_2','M',1);
INSERT INTO t_student (NAME,sex,group_id) VALUES('zjd_3','M',2);
INSERT INTO t_student (NAME,sex,group_id) VALUES('zjd_4','W',2);
INSERT INTO t_student (NAME,sex,group_id) VALUES('zjd_5','W',2);
INSERT INTO t_student (NAME,sex,group_id) VALUES('zjd_6','W',2);
INSERT INTO t_student (NAME,sex,group_id) VALUES('zjd_7','M',3);
INSERT INTO t_student (NAME,sex,group_id) VALUES('zjd_8','W',4);
INSERT INTO t_student (NAME,sex,group_id) VALUES('zjd_9','W',4);
================================================================
mysql> create view view_test2 as select count(name) from t_student;
Query OK, 0 rows affected (0.71 sec)
mysql> select * from view_test2;
+-------------+
| count(name) |
+-------------+
|      9 |
+-------------+
1 row in set (0.01 sec)
Copy after login

2.2.3 Encapsulates the view that implements the sorting function (ORDER BY) query statement:

Example:

mysql> create view view_test3 as select name from t_student order by id desc;
Query OK, 0 rows affected (0.06 sec)
mysql> select * from view_test3;
+-------+
| name |
+-------+
| zjd_9 |
| zjd_8 |
| zjd_7 |
| zjd_6 |
| zjd_5 |
| zjd_4 |
| zjd_3 |
| zjd_2 |
| zjd_1 |
+-------+
9 rows in set (0.00 sec)
Copy after login

2.2.4 Encapsulates the view that implements the join query statement in the table:

Example: (Name of second group of students)

mysql> create view view_test5 as select s.name from t_student s,t_group g where s.group_id=g.id and g.id=2;
Query OK, 0 rows affected (0.07 sec)
mysql> select * from view_test5;
+-------+
| name |
+-------+
| zjd_3 |
| zjd_4 |
| zjd_5 |
| zjd_6 |
+-------+
4 rows in set (0.00 sec)
Copy after login

2.2.5 Encapsulates views that implement query statements for out-of-table joins (LEFT JOIN and RIGHT JOIN):

Example: (Second group of student names)

mysql> create view view_test6 as select s.name from t_student s left join t_group g on s.group_id=g.id where g.id=2;
Query OK, 0 rows affected (0.09 sec)
mysql> select * from view_test6;
+-------+
| name |
+-------+
| zjd_3 |
| zjd_4 |
| zjd_5 |
| zjd_6 |
+-------+
4 rows in set (0.01 sec)
Copy after login

2.2.6 encapsulates the view that implements subquery related query statements:

Example:

mysql> create view view_test7 as select s.name from t_student s where s.id in(select id from t_group);
Query OK, 0 rows affected (0.08 sec)
mysql> select * from view_test7;
+-------+
| name |
+-------+
| zjd_1 |
| zjd_2 |
| zjd_3 |
| zjd_4 |
| zjd_5 |
+-------+
5 rows in set (0.00 sec)
Copy after login

2.2.7 Encapsulates the view that implements record union (UNION and UNION ALL) query statements:

mysql> create view view_test8 as select id,name from t_student union all select id,name from t_group;
Query OK, 0 rows affected (0.08 sec)
mysql> select * from view_test8;
+----+---------+
| id | name  |
+----+---------+
| 1 | zjd_1  |
| 2 | zjd_2  |
| 3 | zjd_3  |
| 4 | zjd_4  |
| 5 | zjd_5  |
| 6 | zjd_6  |
| 7 | zjd_7  |
| 8 | zjd_8  |
| 9 | zjd_9  |
| 1 | group_1 |
| 2 | group_2 |
| 3 | group_3 |
| 4 | group_4 |
| 5 | group_5 |
+----+---------+
14 rows in set (0.01 sec)

Copy after login

3. View view:
3.1 SHOW TABLES statement to view view name:
When executing the SHOW TABLES statement, not only the name of the table can be displayed, but also the name of the view can be displayed.

Example:

mysql> show tables;
+------------------+
| Tables_in_zhaojd |
+------------------+
| t_group     |
| t_product    |
| t_student    |
| v_product    |
| view_test1    |
| view_test2    |
| view_test3    |
| view_test4    |
| view_test5    |
| view_test6    |
| view_test8    |
+------------------+
11 rows in set (0.00 sec)
Copy after login

3.2 SHOW TABLE STATUS statement to view view details:

Like the SHOW TABLES statement, the SHOW TABLE STATUS statement not only displays the detailed information of the table, but also displays the detailed information of the view.

The syntax is as follows:
SHOW TABLE STATUS [FROM db_name] [LIKE 'pattern']
//The parameter db_name is used to set the database. SHOW TABLES STATUS means that the detailed information of the tables and views of the set library will be displayed.
//Set the LIKE keyword to view detailed information about a specific table or view. For example: SHOW TABLE STATUS FROM zhaojd LIKE 't_group' G
Example:

mysql> show table status from zhaojd \G
*************************** 1. row ***************************
      Name: t_group
     Engine: InnoDB
    Version: 10
   Row_format: Compact
      Rows: 5
 Avg_row_length: 3276
  Data_length: 16384
Max_data_length: 0
  Index_length: 0
   Data_free: 7340032
 Auto_increment: 6
  Create_time: 2016-08-19 16:26:06
  Update_time: NULL
   Check_time: NULL
   Collation: utf8_general_ci
    Checksum: NULL
 Create_options:
    Comment:
============================================================= 
      Name: view_test8
     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
Copy after login

3.3 SHOW CREATE VIEW语句查看视图定义信息:

语法为:
SHOW CREATE VIEW viewname;
示例:

 mysql> show create view view_test8 \G
*************************** 1. row ***************************
View: view_test8
Create View: CREATE ALGORITHM=UNDEFINED DEFINER=`root`@`localhost` SQL SECURITY DEFINER VIEW `view_test8` AS select `t_student`.`id` AS `id`,
`t_student`.`NAME` AS `name` from `t_student` union all select `t_group`.`id` AS `id`,`t_group`.`NAME` AS `name` from `t_group`
character_set_client: utf8
collation_connection: utf8_general_ci
1 row in set (0.00 sec)
//根据执行结果可以发现,SHOW CREATE VIEW语句返回两个字段,分别为表示视图名的View字段和关于视图定义的Create view字段。
Copy after login

3.4 DESCRIBE | DESC 语句查看视图定义信息:

语法为:
DESCRIBE | DESC viewname;
示例:

mysql> desc view_test8;
+-------+-------------+------+-----+---------+-------+
| Field | Type    | Null | Key | Default | Extra |
+-------+-------------+------+-----+---------+-------+
| id  | int(11)   | NO  |   | 0    |    |
| name | varchar(20) | YES |   | NULL  |    |
+-------+-------------+------+-----+---------+-------+
2 rows in set (0.02 sec) 
Copy after login

3.5 通过系统表查看视图信息:
当MySQL安装成功后,会自动创建系统数据库infomation_schema。在该数据库中存在一个包含视图信息的表格,可以通过查看表格views来查看所有视图的相关信息。

示例:

mysql> use information_schema;
Database changed
mysql> select * from views where table_name='view_test8' \G
*************************** 1. row ***************************
    TABLE_CATALOG: def
    TABLE_SCHEMA: zhaojd
     TABLE_NAME: view_test8
   VIEW_DEFINITION: select `zhaojd`.`t_student`.`id`AS`id`,`zhaojd`.`t_student`.`NAME` AS `name` from `zhaojd`.`t_student` union all select `zhaojd`.`t_group`.`id` AS`id`,`zhaojd`.`t_group`.`NAME` AS `name` from `zhaojd`.`t_group`
    CHECK_OPTION: NONE
    IS_UPDATABLE: NO
       DEFINER: root@localhost
    SECURITY_TYPE: DEFINER
CHARACTER_SET_CLIENT: utf8
COLLATION_CONNECTION: utf8_general_ci
1 row in set (0.01 sec)
Copy after login

4.删除视图:
在删除视图时首先要确保拥有删除视图的权限。

语法为:
DROP VIEW view_name [,view_name] ......
//从语法可以看出,DROP VIEW一次可以删除多个视图
示例:

mysql> use zhaojd;
Database changed
mysql> show tables;
+------------------+
| Tables_in_zhaojd |
+------------------+
| t_group     |
| t_product    |
| t_student    |
| v_product    |
| view_test1    |
| view_test2    |
| view_test3    |
| view_test4    |
| view_test5    |
| view_test6    |
| view_test8    |
+------------------+
11 rows in set (0.00 sec)
mysql> drop view view_test1, view_test2;
Query OK, 0 rows affected (0.01 sec)
mysql> show tables;
+------------------+
| Tables_in_zhaojd |
+------------------+
| t_group     |
| t_product    |
| t_student    |
| v_product    |
| view_test3    |
| view_test4    |
| view_test5    |
| view_test6    |
| view_test8    |
+------------------+
9 rows in set (0.00 sec)
Copy after login

5.修改视图:
5.1 CREATE OR REPLACE VIEW语句修改视图:
对于已经创建好的表,尤其是已经有大量数据的表,通过先删除,然后再按照新的表定义重新建表的方式来修改表,需要做很多额外的工作,例如数据的重载等。可是对于视图来说,由于是“虚表”,并没有存储数据,所以完全可以通过该方式来修改视图。

实现思路就是:先删除同名的视图,然后再根据新的需求创建新的视图即可。

DROP VIEW view_name; 
CREATE VIEW view_name as 查询语句;
Copy after login

但是如果每次修改视图,都是先删除视图,然后再次创建一个同名的视图,则显得非常麻烦。于是MySQL提供了更方便的实现替换的创建视图的语法,完整语法为:

CREATE OR REPLACE VIEW view_name as 查询语句;

 5.2 ALTER语句修改视图:

语法为:

ALTER VIEW view_name as 查询语句;

6.利用视图操作基本表: 
再MySQL中可以通常视图检索基本表数据,这是视图最基本的应用,除此之后还可以通过视图修改基本表中的数据。 
6.1检索(查询)数据: 
    通过视图查询数据,与通过表进行查询完全相同,只不过通过视图查询表更安全,更简单实用。只需要把表名换成视图名即可。 
6.2利用视图操作基本表数据: 
    由于视图是“虚表”,所以对视图数据进行的更新操作,实际上是对其基本表数据进行的更新操作。在具体更新视图数据时,需要注意以下两点;
    1. 对视图数据进行添加、删除直接影响基本表。
    2. 视图来自于多个基本表时,不允许添加、删除数据。
    视图中的添加数据操作、删除数据操作、更新数据操作的语法同表完全相同。只是将表名换成视图名即可。

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。

Statement of this Website
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

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

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

MySQL's Role: Databases in Web Applications MySQL's Role: Databases in Web Applications Apr 17, 2025 am 12:23 AM

The main role of MySQL in web applications is to store and manage data. 1.MySQL efficiently processes user information, product catalogs, transaction records and other data. 2. Through SQL query, developers can extract information from the database to generate dynamic content. 3.MySQL works based on the client-server model to ensure acceptable query speed.

How to start mysql by docker How to start mysql by docker Apr 15, 2025 pm 12:09 PM

The process of starting MySQL in Docker consists of the following steps: Pull the MySQL image to create and start the container, set the root user password, and map the port verification connection Create the database and the user grants all permissions to the database

Laravel Introduction Example Laravel Introduction Example Apr 18, 2025 pm 12:45 PM

Laravel is a PHP framework for easy building of web applications. It provides a range of powerful features including: Installation: Install the Laravel CLI globally with Composer and create applications in the project directory. Routing: Define the relationship between the URL and the handler in routes/web.php. View: Create a view in resources/views to render the application's interface. Database Integration: Provides out-of-the-box integration with databases such as MySQL and uses migration to create and modify tables. Model and Controller: The model represents the database entity and the controller processes HTTP requests.

Solve database connection problem: a practical case of using minii/db library Solve database connection problem: a practical case of using minii/db library Apr 18, 2025 am 07:09 AM

I encountered a tricky problem when developing a small application: the need to quickly integrate a lightweight database operation library. After trying multiple libraries, I found that they either have too much functionality or are not very compatible. Eventually, I found minii/db, a simplified version based on Yii2 that solved my problem perfectly.

How to install mysql in centos7 How to install mysql in centos7 Apr 14, 2025 pm 08:30 PM

The key to installing MySQL elegantly is to add the official MySQL repository. The specific steps are as follows: Download the MySQL official GPG key to prevent phishing attacks. Add MySQL repository file: rpm -Uvh https://dev.mysql.com/get/mysql80-community-release-el7-3.noarch.rpm Update yum repository cache: yum update installation MySQL: yum install mysql-server startup MySQL service: systemctl start mysqld set up booting

Centos install mysql Centos install mysql Apr 14, 2025 pm 08:09 PM

Installing MySQL on CentOS involves the following steps: Adding the appropriate MySQL yum source. Execute the yum install mysql-server command to install the MySQL server. Use the mysql_secure_installation command to make security settings, such as setting the root user password. Customize the MySQL configuration file as needed. Tune MySQL parameters and optimize databases for performance.

Laravel framework installation method Laravel framework installation method Apr 18, 2025 pm 12:54 PM

Article summary: This article provides detailed step-by-step instructions to guide readers on how to easily install the Laravel framework. Laravel is a powerful PHP framework that speeds up the development process of web applications. This tutorial covers the installation process from system requirements to configuring databases and setting up routing. By following these steps, readers can quickly and efficiently lay a solid foundation for their Laravel project.

MySQL vs. Other Programming Languages: A Comparison MySQL vs. Other Programming Languages: A Comparison Apr 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.

See all articles