13.2.8 DML语句语法 2.update语句

13.2.8 DML语句语法 2.update语句

update语句用于修改数据表的记录,每次可以修改多条记录通过使用where子句限定修改哪些记录where子句是一个条件表达式,该条件表达式类似于Java语言的if,只有符合该条件的记录才会被修改。没有where子句则意味着where表达式的值总是true,即该表的所有记录都会被修改

语法格式

update语句的语法格式如下:

1
2
3
update table_name
set column1=value [,column2=value2,...]
[where condition];

使用update语句不仅可以一次修改多条记录,也可以一次修改多列。修改多列都是通过在set关键字后使用column1=value1,column2=value2…来实现的,修改多列的值之间以英文逗号(,)隔开。

更新列中的所有内容

下面的SQL语句将会把teacher_table2表中所有记录的teacher_name列的值都改为'孙悟空'

1
2
update teacher_table2
set teacher_name='孙悟空';

运行效果:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
mysql> select * from teacher_table2;
+------------+--------------+
| teacher_id | teacher_name |
+------------+--------------+
| 1 | xyz |
| 2 | abx |
+------------+--------------+
2 rows in set

mysql> update teacher_table2
set teacher_name='孙悟空';
Query OK, 2 rows affected
Rows matched: 2 Changed: 2 Warnings: 0

mysql> select * from teacher_table2;
+------------+--------------+
| teacher_id | teacher_name |
+------------+--------------+
| 1 | 孙悟空 |
| 2 | 孙悟空 |
+------------+--------------+
2 rows in set

更新指定记录

也可以通过添加where条件来指定只修改特定记录,如下SQL语句所示:

1
2
3
update teacher_table2
set teacher_name='美猴王'
where teacher_id>=2;

运行效果:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
mysql> select * from teacher_table2;
+------------+--------------+
| teacher_id | teacher_name |
+------------+--------------+
| 1 | 孙悟空 |
| 2 | 孙悟空 |
+------------+--------------+
2 rows in set

mysql> update teacher_table2
set teacher_name='美猴王'
where teacher_id>=2;
Query OK, 1 row affected
Rows matched: 1 Changed: 1 Warnings: 0

mysql> select * from teacher_table2;
+------------+--------------+
| teacher_id | teacher_name |
+------------+--------------+
| 1 | 孙悟空 |
| 2 | 美猴王 |
+------------+--------------+
2 rows in set