MySQL UPDATE 更新

用 UPDATE 修改已有数据,牢记先加 WHERE。

Beginner
Key PointsUPDATE 一定要带 WHERE,否则会把整张表改掉——这是生产事故第一名。

基本语法

SQL
UPDATE users
SET age = 29, email = 'alice2@example.com'
WHERE username = 'alice';
Output
Query OK, 1 row affected (0.01 sec)
Rows matched: 1  Changed: 1  Warnings: 0

不加 WHERE 的后果

SQL
UPDATE users SET age = 0;     -- 全表年龄清零!
Output
Query OK, 4 rows affected (0.01 sec)
Rows matched: 4  Changed: 4  Warnings: 0
Before UPDATE/DELETE, run SELECT COUNT(*) with the same WHERE to confirm the row count, then switch to the write. MySQL 8.0 also supports UPDATE ... ORDER BY ... LIMIT n.

Friends & Partners