# 可更新视图

在本教程中，我们将向您展示如何通过视图创建可更新视图并更新基础表中的数据。

## MySQL可更新视图简介

在MySQL中，视图不仅是可查询的，而且是可更新的。这意味着您可以使用[INSERT](http://www.yiibai.com/mysql/insert-statement.html)或[UPDATE](http://www.yiibai.com/mysql/update-data.html)语句通过可更新视图插入或更新基表的行。 另外，您可以使用[DELETE](http://www.yiibai.com/mysql/delete-statement.html)语句通过视图删除底层表的行。

但是，要创建可更新[视图](http://www.yiibai.com/mysql/introduction-sql-views.html)，定义视图的[SELECT语句](http://www.yiibai.com/mysql/select-statement-query-data.html)不能包含以下任何元素：

* [聚合函数](http://www.yiibai.com/mysql/aggregate-functions.html)，如：[MIN](http://www.yiibai.com/mysql/min.html)，[MAX](http://www.yiibai.com/mysql/max-function.html)，[SUM](http://www.yiibai.com/mysql/sum.html)，[AVG](http://www.yiibai.com/mysql/avg.html)，[COUNT](http://www.yiibai.com/mysql/count.html)等。
* [DISTINCT子句](http://www.yiibai.com/mysql/distinct.html)
* [GROUP BY子句](http://www.yiibai.com/mysql/group-by.html)
* [HAVING子句](http://www.yiibai.com/mysql/having.html)
* [UNION](http://www.yiibai.com/mysql/sql-union-mysql.html)或`UNION ALL`子句
* [左连接](http://www.yiibai.com/mysql/left-join.html)或外连接。
* SELECT子句中的[子查询](http://www.yiibai.com/mysql/subquery.html)或引用该表的[WHERE子句](http://www.yiibai.com/mysql/where.html)中的子查询出现在`FROM`子句中。
* 引用`FROM`子句中的不可更新视图
* 仅引用文字值
* 对基表的任何列的多次引用

如果使用[TEMPTABLE算法](http://www.yiibai.com/mysql/create-sql-views-mysql.html)创建视图，则无法更新视图。

> 请注意，有时可以使用[内部连接](http://www.yiibai.com/mysql/inner-join.html)创建基于多个表的可更新视图。

## MySQL可更新视图示例

让我们先来看看如何创建一个可更新的视图。

首先，基于[示例数据库(yiibaidb)](http://www.yiibai.com/mysql/sample-database.html)中的`offices`表创建一个名为`officeInfo`的视图。该视图指的是`offices`表中的三列：`officeCode`，`phone` 和 `city`。

```sql
CREATE VIEW officeInfo
 AS 
   SELECT officeCode, phone, city
   FROM offices;
```

接下来，使用以下语句从`officeInfo`视图中查询数据：

```sql
SELECT 
    *
FROM
    officeInfo;
```

执行上面查询语句，得到以下结果 -

```sql
mysql> SELECT * FROM officeInfo;
+------------+------------------+---------------+
| officeCode | phone            | city          |
+------------+------------------+---------------+
| 1          | +1 650 219 4782  | San Francisco |
| 2          | +1 215 837 0825  | Boston        |
| 3          | +1 212 555 3000  | NYC           |
| 4          | +33 14 723 4404  | Paris         |
| 5          | +86 33 224 5000  | Beijing       |
| 6          | +61 2 9264 2451  | Sydney        |
| 7          | +44 20 7877 2041 | London        |
+------------+------------------+---------------+
7 rows in set
```

然后，使用以下[UPDATE](http://www.yiibai.com/mysql/update-data.html)语句通过`officeInfo视`图更改`officeCode`的值为：`4`的办公室电话号码。

```sql
UPDATE officeInfo 
SET 
    phone = '+86 089866668888'
WHERE
    officeCode = 4;
```

最后，验证更改结果，通过执行以下查询来查询`officeInfo`视图中的数据：

```sql
mysql> SELECT 
    *
FROM
    officeInfo
WHERE
    officeCode = 4;

+------------+------------------+-------+
| officeCode | phone            | city  |
+------------+------------------+-------+
| 4          | +86 089866668888 | Paris |
+------------+------------------+-------+
1 row in set
```

## 检查可更新视图信息

通过从`information_schema`数据库中的`views`表查询`is_updatable`列来检查数据库中的视图是否可更新。

以下查询语句将查询`yiibaidb`数据库获取所有视图，并显示哪些视图是可更新的。

```sql
SELECT 
    table_name, is_updatable
FROM
    information_schema.views
WHERE
    table_schema = 'yiibaidb';
```

执行上面查询语句，得到以下结果 -

```sql
+------------------+--------------+
| table_name       | is_updatable |
+------------------+--------------+
| aboveavgproducts | YES          |
| bigsalesorder    | YES          |
| customerorders   | NO           |
| officeinfo       | YES          |
| saleperorder     | NO           |
+------------------+--------------+
5 rows in set
```

## 通过视图删除行

首先，创建一个名为`items`的表，在`items`表中插入一些行，并创建一个查询包含价格大于`700`的项的视图。

```sql
USE testdb;
-- create a new table named items
CREATE TABLE items (
    id INT AUTO_INCREMENT PRIMARY KEY,
    name VARCHAR(100) NOT NULL,
    price DECIMAL(11 , 2 ) NOT NULL
);

-- insert data into the items table
INSERT INTO items(name,price) 
VALUES('Laptop',700.56),('Desktop',699.99),('iPad',700.50) ;

-- create a view based on items table
CREATE VIEW LuxuryItems AS
    SELECT 
        *
    FROM
        items
    WHERE
        price > 700;
-- query data from the LuxuryItems view
SELECT 
    *
FROM
    LuxuryItems;
```

执行上面查询语句后，得到以下结果 -

```sql
+----+--------+--------+
| id | name   | price  |
+----+--------+--------+
|  1 | Laptop | 700.56 |
|  3 | iPad   | 700.5  |
+----+--------+--------+
2 rows in set
```

**其次**，使用`DELETE`语句来删除`id`为`3`的行。

```sql
DELETE FROM LuxuryItems 
WHERE
    id = 3;
```

MySQL返回一条消息，表示有`1`行受到影响。

```sql
Query OK, 1 row affected
```

**第三步**，再次通过视图检查数据。

```sql
mysql> SELECT * FROM LuxuryItems;
+----+--------+--------+
| id | name   | price  |
+----+--------+--------+
|  1 | Laptop | 700.56 |
+----+--------+--------+
1 row in set
```

**第四步**，还可以从基表`items`查询数据，以验证`DELETE`语句是否实际删除了该行。

```sql
mysql> SELECT  * FROM items;
+----+---------+--------+
| id | name    | price  |
+----+---------+--------+
|  1 | Laptop  | 700.56 |
|  2 | Desktop | 699.99 |
+----+---------+--------+
2 rows in set
```

如上面所示，`ID`为`3`的行在基表中被删除。

在本教程中，我们向您展示了如何通过创建可更新视图，并更新基础表中的数据。


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://hezhiqiang-book.gitbook.io/mysql/di-wu-zhang/ke-geng-xin-shi-tu.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
