> ## Documentation Index
> Fetch the complete documentation index at: https://villagesql.com/docs/llms.txt
> Use this file to discover all available pages before exploring further.

# MySQL UPDATE

> MySQL UPDATE 语句如何修改表中已有的行，Rows matched 和 Changed 各自统计什么，以及省略 WHERE 时会发生什么。

> [card] [VillageSQL is a drop-in replacement for MySQL with extensions.](https://villagesql.com/docs/en/8.4/stable/install-server.md)
>
> All examples on this page work on VillageSQL. Install Now →

`UPDATE` 修改已经存在的行。`WHERE` 决定修改哪些行，它是 1 行和整个表之间唯一的屏障。

这些示例使用来自 [INSERT](https://villagesql.com/docs/zh/tutorial/insert.md) 的 `sakila_practice` 数据库。开始之前，请再次运行那里的设置代码块，然后用 `mysql -u root -p sakila_practice` 打开客户端。

## UPDATE 的工作原理

```sql theme={null}
UPDATE TABLE_NAME
SET COLUMN_NAME = NEW_VALUE
WHERE CONDITION;
```

把 `TABLE_NAME` 替换为表，`COLUMN_NAME` 替换为要修改的列，`NEW_VALUE` 替换为要放进去的值，`CONDITION` 替换为挑选行的测试。

`WHERE` 的工作方式与它在 `SELECT` 中完全一样，而这正是写 `UPDATE` 最安全的方法：先把它作为 `SELECT` 运行，看看那些行，然后把 `SELECT ...` 改成 `UPDATE ... SET ...`，`WHERE` 保持不动。

## 示例

### 修改 1 行

```sql theme={null}
UPDATE member SET active = 0 WHERE member_id = 2;
```

```text theme={null}
Query OK, 1 row affected (0.00 sec)
Rows matched: 1  Changed: 1  Warnings: 0
```

```sql theme={null}
SELECT member_id, first_name, last_name, active FROM member;
```

```text theme={null}
+-----------+------------+-----------+--------+
| member_id | first_name | last_name | active |
+-----------+------------+-----------+--------+
|         1 | Mary       | Smith     |      1 |
|         2 | Patricia   | Johnson   |      0 |
|         3 | Linda      | Williams  |      0 |
+-----------+------------+-----------+--------+
3 rows in set (0.00 sec)
```

### Matched 和 Changed 统计的是不同的东西

把同一条语句再运行一次。

```sql theme={null}
UPDATE member SET active = 0 WHERE member_id = 2;
```

```text theme={null}
Query OK, 0 rows affected (0.00 sec)
Rows matched: 1  Changed: 0  Warnings: 0
```

`WHERE` 仍然找到了那一行，所以 `Rows matched` 是 1。那一行已经是 0，所以什么都没写，`Changed` 是 0。把这 2 个数字放在一起读：`matched 0` 表示 `WHERE` 什么都没找到，这与 `changed 0` 是不同的问题，后者表示您要求的值是那些行已经有的值。

### 一次修改几列

用逗号分隔赋值，不要用 `AND`。

```sql theme={null}
UPDATE member
SET last_name = 'Smith-Davis', email = 'mary.smith-davis@example.com'
WHERE member_id = 1;
```

```text theme={null}
Query OK, 1 row affected (0.00 sec)
Rows matched: 1  Changed: 1  Warnings: 0
```

```sql theme={null}
SELECT member_id, first_name, last_name, email FROM member WHERE member_id = 1;
```

```text theme={null}
+-----------+------------+-------------+------------------------------+
| member_id | first_name | last_name   | email                        |
+-----------+------------+-------------+------------------------------+
|         1 | Mary       | Smith-Davis | mary.smith-davis@example.com |
+-----------+------------+-------------+------------------------------+
1 row in set (0.00 sec)
```

## UPDATE 遇到的约束与 INSERT 相同

把另一行已持有的值移进 `UNIQUE` 列会以同样的方式失败，该行保留原有的值。

```sql theme={null}
UPDATE member SET email = 'patricia.johnson@example.com' WHERE member_id = 3;
```

```text theme={null}
ERROR 1062 (23000): Duplicate entry 'patricia.johnson@example.com' for key 'member.uq_member_email'
```

## 没有 WHERE 它会修改每一行

没有确认步骤。语句运行，表中的每一行都取新值。

一个会话设置可以替您拒绝这种形式。安全更新模式会拒绝既不在 `WHERE` 中测试键列也不带 `LIMIT` 的 `UPDATE` 或 `DELETE`，除非您主动要求，否则它是关闭的。

```sql theme={null}
SET SESSION sql_safe_updates = 1;
UPDATE member SET active = 1;
```

```text theme={null}
Query OK, 0 rows affected (0.00 sec)

ERROR 1175 (HY000): You are using safe update mode and you tried to update a table without a WHERE that uses a KEY column.
```

用 `mysql -u root -p --safe-updates sakila_practice` 启动客户端，就能从第一条语句起获得这个保护。这个标志做的不止设置这 1 个变量：它还通过 `sql_select_limit` 把 `SELECT` 限制在 1,000 行，并通过 `max_join_size` 限制连接，所以针对大表的读取会在不作提示的情况下返回不完整的结果。`ERROR 1175` 表示这个保护拦住了您。

当语句确实要修改每一行时，再把它关掉。

```sql theme={null}
SET SESSION sql_safe_updates = 0;
```

```text theme={null}
Query OK, 0 rows affected (0.00 sec)
```

保护关闭后，语句就能运行。

```sql theme={null}
UPDATE member SET active = 1;
```

```text theme={null}
Query OK, 2 rows affected (0.00 sec)
Rows matched: 3  Changed: 2  Warnings: 0
```

```sql theme={null}
SELECT member_id, first_name, active FROM member;
```

```text theme={null}
+-----------+------------+--------+
| member_id | first_name | active |
+-----------+------------+--------+
|         1 | Mary       |      1 |
|         2 | Patricia   |      1 |
|         3 | Linda      |      1 |
+-----------+------------+--------+
3 rows in set (0.00 sec)
```

`Rows matched: 3  Changed: 2`，因为有 1 位会员已经是活跃状态。

整表更新有时恰恰是对的。把每个余额提高 5% 只需 1 条语句，新值由旧值算出。

```sql theme={null}
UPDATE account SET balance = balance * 1.05;
```

```text theme={null}
Query OK, 2 rows affected (0.00 sec)
Rows matched: 2  Changed: 2  Warnings: 0
```

```sql theme={null}
SELECT * FROM account;
```

```text theme={null}
+------------+------------------+---------+
| account_id | owner            | balance |
+------------+------------------+---------+
|          1 | Mary Smith       |  525.00 |
|          2 | Patricia Johnson |  262.50 |
+------------+------------------+---------+
2 rows in set (0.00 sec)
```

`balance = balance * 1.05` 读取每一行的当前值，所以每一行都得到自己的答案。

## 总结

* 写 `UPDATE table SET column = value WHERE condition` 来修改已有的行。
* 先把 `WHERE` 作为 `SELECT` 运行，然后只改语句的开头。
* 把 `Rows matched` 和 `Changed` 当作 2 个独立的事实来读。
* 用逗号分隔多个赋值。
* 预期 `UPDATE` 会遇到与 `INSERT` 相同的 `UNIQUE` 和 `NOT NULL` 规则。
* 打开安全更新模式，并把 `ERROR 1175` 理解为保护在起作用。

## 另请参阅

* [WHERE](https://villagesql.com/docs/zh/tutorial/where.md) — 决定哪些行被修改的子句
* [DELETE](https://villagesql.com/docs/zh/tutorial/delete.md) — 删除行而不是修改行
* [Upsert](https://villagesql.com/docs/zh/tutorial/upsert.md) — 更新已有的行，或在没有时插入一行
* [事务](https://villagesql.com/docs/zh/tutorial/transactions.md) — 撤销一次错误的 UPDATE


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.