在本教程中,您将学习如何使用sql update
语句来修改表中现有行的数据。
要更改表中的现有数据,请使用update
语句。 以下是update
语句的语法:
update table_name
set column1 = value1,
column2 = value2
where
condition;
在上面的语法中 -
update
子句中指明要更新的表。set
子句中指定要修改的列。 set
子句中未列出的列的值不会被修改。where
子句中要更新的行。update
语句根据where
子句中的条件影响表中的一行或多行。 例如,如果where
子句包含主键表达式,则update
语句仅更改一行。
但是,将修改where
条件评估为true
的任何行。 因为where
子句是可选的,所以,如果省略它,表中的所有行都将受到影响。
我们将使用employees
和dependents
表来演示如何使用update
语句。
sql update更新一行示例
假设有一个员工编号(employee_id
)的值为:192
,在employees
表中查询数据记录,如下所示 -
mysql> select first_name,last_name from employees where employee_id=192;
+------------+-----------+
| first_name | last_name |
+------------+-----------+
| sarah | yang |
+------------+-----------+
1 row in set
要将last_name
字段的值从yang
改为zhang
,请使用以下update
语句:
update employees
set
last_name = 'zhang'
where
employee_id = 192;
数据库系统更新了employee_id
为192
的记录last_name
列的值。可以使用以下select
语句对其进行验证。
select
employee_id,
first_name,
last_name
from
employees
where
employee_id = 192;
执行上面查询语句,得到以下结果 -
+-------------+------------+-----------+
| employee_id | first_name | last_name |
+-------------+------------+-----------+
| 192 | sarah | zhang |
+-------------+------------+-----------+
1 row in set
sql update多行示例
现在,要把所有工资低于2500
的员工全部提高到3000
,在更新数据之前,让我们先来看看有有哪些工资低于2500
的员工。
select
employee_id,
first_name,
last_name,salary
from
employees
where
salary<3000;
+-------------+------------+-----------+--------+
| employee_id | first_name | last_name | salary |
+-------------+------------+-----------+--------+
| 116 | shelli | zhang | 2900 |
| 117 | sigal | zhang | 2800 |
| 118 | guy | zhang | 2600 |
| 119 | karen | zhang | 2500 |
| 126 | irene | liu | 2700 |
+-------------+------------+-----------+--------+
5 rows in set
执行以下update
语句,以更新工资为:3000
。
update
employees
set
salary=3000
where
salary<3000;
带有子查询示例的sql update
有时,当员工更改姓氏(last_name
)时,只更新employees
表而不更新dependents
表。
要确保子项的姓氏(last_name
)始终与employees
表中父项的姓氏(last_name
)匹配,请使用以下语句:
update dependents
set last_name = (
select
last_name
from
employees
where
employee_id = dependents.employee_id
);
由于省略了where
子句,因此update
语句更新了dependents
表中的所有行。在set
子句中,我们使用子查询而不是使用文字值来从employees
表中获取相应的last_name
值。
在本教程中,我们演示了如何使用sql update
语句来修改表中的现有数据。