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 |