【MySQL】基本查询-3. 修改

时间:2024-09-30 17:32:59

3.1 update

如果想修改表中已经插入的数据,可以使用update语句,该语句允许更改一个或多个表中的行的一个或多个列的值

基本语法如下:

update table_name  
set column1 = value1, column2 = value2, ...  
where...
order by...

value: 可以是表达式

它是对查询到的结果列值进行更新,所以尽量要带where筛选出指定的列进行更新,否则就是对整表更新

将孙悟空的数学更新成80分:

mysql> update exam
    -> set math=80
    -> where name='孙悟空';
Query OK, 1 row affected (0.01 sec)
Rows matched: 1  Changed: 1  Warnings: 0

将曹孟德同学的数学成绩变更为 60 分,语文成绩变更为 70 分:

mysql> update exam 
    -> set math=60, chinese=70
    -> where name='曹孟德';
Query OK, 1 row affected (0.01 sec)
Rows matched: 1  Changed: 1  Warnings: 0

将总成绩倒数前三的 3 位同学的数学成绩加上 30 分:

mysql> update exam  
	-> set math=math + 30 
	-> order by chinese + math + english asc 
	-> limit 3;
Query OK, 3 rows affected (0.01 sec)
Rows matched: 3  Changed: 3  Warnings: 0

把所有同学的语文成绩变成原来的2倍:

# 不带where子句相当于整表更新 
mysql> update exam
    -> set chinese = chinese * 2;
Query OK, 7 rows affected (0.01 sec)
Rows matched: 7  Changed: 7  Warnings: 0

最后想说的是要慎用update,一定注意要带上where子句,否则误操作会导致整个表的数据丢失