16.2 更新数据
表中有数据之后,接下来可以对数据进行更新操作,MySQL中使用UPDATE语句更新表中的记录,可以更新特定的行或者同时更新所有的行。基本语法结构如下:
UPDATE table_name SET column_name1 = value1,column_name2=value2,…,column_namen=valuen WHERE (condition);
“column_name1,column_name2,…,column_namen”为指定更新的字段的名称;“value1, value2,…valuen”为相对应的指定字段的更新值;condition指定更新的记录需要满足的条件。更新多个列时,每个“列-值”对之间用逗号隔开,最后一列之后不需要逗号。
【例16.8】在表person中,更新id值为10的记录,将age字段值改为15,将name字段值改为LiMing,SQL语句如下:
UPDATE person SET age = 15, name= 'LiMing' WHERE id = 10;
更新操作执行前可以使用SELECT语句查看当前的数据:
mysql> SELECT * FROM person WHERE id=10;
+---- | +------- | +----- | +---------+ |
id | name | age | info |
+---- | +------- | +----- | +---------+ |
10 | Harry | 20 | student |
+---- | +------- | +----- | +---------+ |
由结果可以看到更新之前,id等于10的记录的name字段值为harry,age字段值为20,下面使用UPDATE语句更新数据,语句执行结果如下:
mysql> UPDATE person SET age = 15, name='LiMing' WHERE id = 10; Query OK, 1 row affected (0.00 sec) Rows matched: 1 Changed: 1 Warnings: 0
语句执行完毕,查看执行结果:
mysql> SELECT * FROM person WHERE id=10;
+---- | +-------- | +----- | +---------+ |
id | name | age | info |
+---- | +-------- | +----- | +---------+ |
10 | LiMing | 15 | student |
+---- | +-------- | +----- | +---------+ |
由结果可以看到,id等于10的记录中的name和age字段的值已经成功被修改为指定值。
提 示
保证UPDATE以WHERE子句结束,通过WHERE子句指定被更新的记录所需要满足的条件,如果忽略WHERE子句,MySQL将更新表中所有的行。
【例16.9】在表person中,更新age值为19到22的记录,将info字段值都改为student,SQL语句如下:
UPDATE person SET info= 'student' WHERE id BETWEEN 19 AND 22;
更新操作执行前可以使用SELECT语句查看当前的数据:
mysql> SELECT * FROM person WHERE age BETWEEN 19 AND 22;
+---- | +--------- | +----- | +------------+ |
id | name | age | info |
+---- | +--------- | +----- | +------------+ |
1 | Willam | 20 | sports man |
3 | Green | 21 | Lawyer |
4 | Suse | 22 | dancer |
6 | Dale | 22 | cook |
8 | Harry | 21 | magician |
9 | Harriet | 19 | pianist |
+---- | +--------- | +----- | +------------+ |
可以看到,这些age字段值在19到22之间的记录的info字段值各不相同。下面使用UPDATE语句更新数据,语句执行结果如下:
mysql> UPDATE person SET info='student' WHERE age BETWEEN 19 AND 22; Query OK, 6 rows affected (0.00 sec) Rows matched: 6 Changed: 6 Warnings: 0
语句执行完毕,查看执行结果:
mysql> SELECT * FROM person WHERE age BETWEEN 19 AND 22;
+---- | +--------- | +----- | +---------+ |
id | name | age | info |
+---- | +--------- | +----- | +---------+ |
1 | Willam | 20 | student |
3 | Green | 21 | student |
4 | Suse | 22 | student |
6 | Dale | 22 | student |
8 | Harry | 21 | student |
9 | Harriet | 19 | student |
+---- | +--------- | +----- | +---------+ |
由结果可以看到,UPDATE执行后,成功地将表中符合条件的记录的info字段值都改为student。