Table of Contents
2. Introduction to views
Create view syntax
Modify view syntax
Delete view syntax
3. View operations
Create a view based on a single table
Create a view based on multiple tables
Modify the view
Delete view
Home Database Mysql Tutorial Introduction to MySQL views and operations (with code)

Introduction to MySQL views and operations (with code)

Apr 15, 2019 am 11:26 AM
mysql

This article brings you an introduction to the introduction and operation of MySQL views (with code). It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.

1. Preparation

Create two tables balance (balance table) and customer (customer table) in the MySQL database and insert data.

create table customer(
    id int(10) primary key,
    name char(20) not null,
    role char(20) not null,
    phone char(20) not null,
    sex char(10) not null,
    address char(50) not null
)ENGINE=InnoDB DEFAULT CHARSET=utf8;

#外键为customerId
create table balance(
    id int(10) primary key,
    customerId int(10) not null,
    balance DECIMAL(10,2),
    foreign key(customerId) references customer(id) 

)ENGINE=InnoDB DEFAULT CHARSET=utf8;
Copy after login

Insert 3 pieces of data each into the customer table and balance table.

insert into customer values(0001,"xiaoming",'vip1','12566666','male','江宁区888号');
insert into customer values(0002,"xiaohong",'vip10','15209336760','male','建邺区888号');
insert into customer values(0003,"xiaocui",'vip11','15309336760','female','新街口888号');

insert into balance values(1,0001,900.55);
insert into balance values(2,0002,900.55);
insert into balance values(3,0003,10000);
Copy after login

2. Introduction to views

A view can be simply understood as a virtual table. It is different from the real data table in the database. The data in the view is obtained based on the query of the real table. Views have a similar structure to real tables. Views also support operations such as updating, querying, and deleting real tables. So why do we need views?

a. Improve the security of the real table: The view is virtual, and you can only grant the user the permissions of the view without granting the permissions of the real table, which plays a role in protecting the real table.
b. Customized display of data: Based on the same actual table, data can be customized to display data to users with different needs through different views.
c. Simplify data operations: It is suitable for scenarios where query statements are complex and frequently used, and can be implemented through views.
......

It should be noted that view-related operations require users to have corresponding permissions. The following operations use the root user, and the default user has operating permissions.

Create view syntax

create view <视图名称>  as <select语句>;
Copy after login

Modify view syntax

To modify the view name, you can delete it first and then create it with the same statement.

#更新视图结构
alter view <视图名称>  as <select语句>;
#更新视图数据相当于更新实际表,不适用基于多表创建的视图
update ....
Copy after login

Note: The data of some views cannot be updated, that is, it cannot be updated using update, insert and other statements, such as:

a, select statement contains multiple tables
b, view Contains the having clause
c, and the view contains the distinct keyword
...

Delete view syntax

drop view <视图名称>
Copy after login

3. View operations

Create a view based on a single table

mysql> create view  bal_view 
    -> as
    -> select * from  balance;
Query OK, 0 rows affected (0.22 sec)
Copy after login

After the creation is completed, view the structure and records of bal_view. It can be found that the results obtained by querying data through the view are exactly the same as querying through the real table.

#查询bal_view的结构
mysql> desc bal_view;
+------------+---------------+------+-----+---------+-------+
| Field      | Type          | Null | Key | Default | Extra |
+------------+---------------+------+-----+---------+-------+
| id         | int(10)       | NO   |     | NULL    |       |
| customerId | int(10)       | NO   |     | NULL    |       |
| balance    | decimal(10,2) | YES  |     | NULL    |       |
+------------+---------------+------+-----+---------+-------+
3 rows in set (0.07 sec)
#查询bal_view中的记录
mysql> select  * from bal_view;
+----+------------+----------+
| id | customerId | balance  |
+----+------------+----------+
|  1 |          1 |   900.55 |
|  2 |          2 |   900.55 |
|  3 |          3 | 10000.00 |
+----+------------+----------+
3 rows in set (0.01 sec)
Copy after login

It is not difficult to draw the conclusion through the statement of creating the view: when the data in the real table changes, the data in the view will also change accordingly. So when the data in the view changes, will the data in the real table change? Let’s experiment and modify the balance of the customer with id=1 to 2000.

mysql> update bal_view set balance=2000 where id=1;
Query OK, 1 row affected (0.05 sec)
Rows matched: 1  Changed: 1  Warnings: 0
Copy after login

Let’s take a look at the data in the real table balance.

mysql> select  * from bal_view where id=1;
+----+------------+---------+
| id | customerId | balance |
+----+------------+---------+
|  1 |          1 | 2000.00 |
+----+------------+---------+
1 row in set (0.03 sec)
Copy after login

Conclusion: When the data in the view table changes, the data in the real table will also change accordingly.

Create a view based on multiple tables

Create a view cus_bal with two fields: customer name and balance.

mysql> create view cus_bal
    -> (cname,bal)
    -> as
    -> select customer.name,balance.balance from customer ,balance
    -> where customer.id=balance.customerId;
Query OK, 0 rows affected (0.05 sec)
#查看cus_bal中的数据
mysql> select *  from  cus_bal;
+----------+----------+
| cname    | bal      |
+----------+----------+
| xiaoming |  2000.00 |
| xiaohong |   900.55 |
| xiaocui  | 10000.00 |
+----------+----------+
3 rows in set (0.28 sec)
Copy after login

Modify the view

Change the cname in the cus_bal view to cusname.

mysql> alter view  cus_bal
    -> (cusname,bal)
    -> as
    -> select customer.name,balance.balance from customer ,balance
    -> where customer.id=balance.customerId;
Query OK, 0 rows affected (0.06 sec)
#查看修改后视图结构。
mysql> desc  cus_bal;
+---------+---------------+------+-----+---------+-------+
| Field   | Type          | Null | Key | Default | Extra |
+---------+---------------+------+-----+---------+-------+
| cusname | char(20)      | NO   |     | NULL    |       |
| bal     | decimal(10,2) | YES  |     | NULL    |       |
+---------+---------------+------+-----+---------+-------+
2 rows in set (0.00 sec)
Copy after login

Modify views created based on multiple tables

mysql> insert into cus_bal(cusname,bal) values ("ee",11);
ERROR 1393 (HY000): Can not modify more than one base table through a join view &#39;rms.cus_bal&#39;
Copy after login

Delete view

Delete view cus_bal

drop view cus_bal;
mysql> drop view cus_bal;
Query OK, 0 rows affected (0.00 sec)
Copy after login

[Related recommendations: MySQL Tutorial

The above is the detailed content of Introduction to MySQL views and operations (with code). For more information, please follow other related articles on the PHP Chinese website!

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.

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.

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

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 and phpMyAdmin: Core Features and Functions MySQL and phpMyAdmin: Core Features and Functions Apr 22, 2025 am 12:12 AM

MySQL and phpMyAdmin are powerful database management tools. 1) MySQL is used to create databases and tables, and to execute DML and SQL queries. 2) phpMyAdmin provides an intuitive interface for database management, table structure management, data operations and user permission management.

See all articles