MySQL UPDATE 语句
MySQL UPDATE 语句
UPDATE
语句用于修改表中的现有记录。
UPDATE 语法
UPDATE 表名
SET 列1 = 值1, 列2 = 值2, ...
WHERE condition;
注意: 在更新表中的记录时要小心!请注意 UPDATE
语句中的 WHERE
子句。WHERE
子句指定要更新的记录。如果省略 WHERE
子句,表中的所有记录都将被更新!
演示数据库
以下是 Northwind 示例数据库中“Customers”表的选段
CustomerID | CustomerName | ContactName | Address | City | PostalCode | Country |
---|---|---|---|---|---|---|
1 |
Alfreds Futterkiste | Maria Anders | Obere Str. 57 | Berlin | 12209 | Germany |
2 | Ana Trujillo Emparedados y helados | Ana Trujillo | Avda. de la Constitución 2222 | México D.F. | 05021 | Mexico |
3 | Antonio Moreno Taquería | Antonio Moreno | Mataderos 2312 | México D.F. | 05023 | Mexico |
4 |
Around the Horn | Thomas Hardy | 120 Hanover Sq. | London | WA1 1DP | UK |
UPDATE 表
以下 SQL 语句使用新的联系人姓名和新的城市更新第一位客户(CustomerID = 1)。
示例
UPDATE Customers
SET ContactName = 'Alfred Schmidt', City = 'Frankfurt'
WHERE CustomerID = 1;
The selection from the "Customers" table will now look like this
CustomerID | CustomerName | ContactName | Address | City | PostalCode | Country |
---|---|---|---|---|---|---|
1 |
Alfreds Futterkiste | Alfred Schmidt | Obere Str. 57 | Frankfurt | 12209 | Germany |
2 | Ana Trujillo Emparedados y helados | Ana Trujillo | Avda. de la Constitución 2222 | México D.F. | 05021 | Mexico |
3 | Antonio Moreno Taquería | Antonio Moreno | Mataderos 2312 | México D.F. | 05023 | Mexico |
4 |
Around the Horn | Thomas Hardy | 120 Hanover Sq. | London | WA1 1DP | UK |
更新多条记录
WHERE
子句决定更新多少条记录。
以下 SQL 语句将把国家为“Mexico”的所有记录的 PostalCode 更新为 00000:
示例
UPDATE Customers
SET PostalCode = 00000
WHERE Country = 'Mexico';
The selection from the "Customers" table will now look like this
CustomerID | CustomerName | ContactName | Address | City | PostalCode | Country |
---|---|---|---|---|---|---|
1 |
Alfreds Futterkiste | Alfred Schmidt | Obere Str. 57 | Frankfurt | 12209 | Germany |
2 | Ana Trujillo Emparedados y helados | Ana Trujillo | Avda. de la Constitución 2222 | México D.F. | 00000 | Mexico |
3 | Antonio Moreno Taquería | Antonio Moreno | Mataderos 2312 | México D.F. | 00000 | Mexico |
4 |
Around the Horn | Thomas Hardy | 120 Hanover Sq. | London | WA1 1DP | UK |
更新警告!
更新记录时要小心。如果省略 WHERE
子句,则所有记录都将被更新!
示例
UPDATE Customers
SET PostalCode = 00000;
The selection from the "Customers" table will now look like this
CustomerID | CustomerName | ContactName | Address | City | PostalCode | Country |
---|---|---|---|---|---|---|
1 |
Alfreds Futterkiste | Alfred Schmidt | Obere Str. 57 | Frankfurt | 00000 | Germany |
2 | Ana Trujillo Emparedados y helados | Ana Trujillo | Avda. de la Constitución 2222 | México D.F. | 00000 | Mexico |
3 | Antonio Moreno Taquería | Antonio Moreno | Mataderos 2312 | México D.F. | 00000 | Mexico |
4 |
Around the Horn | Thomas Hardy | 120 Hanover Sq. | London | 00000 | UK |