MySQL实现数据更新的示例详解
作者:酸菜鱼土豆大侠
一般在更新时会遇到以下场景:
1.所有字段全部更新;
2.根据条件更新字段中的某部分内容;
3.根据不同的条件更新不同的值
以下是几种场景中常用的update方法。
一、方法分类

二、具体用法
(1)根据条件更新值
根据指定条件更新(多列)(全部更新)
把表中 [符合条件的行的] 列名1字段中的值全部修改为值1 [,列名2字段中的值修改为值2]。
update 表名 set 列名1 = 值1 [,列名2=值2] [where 条件];
替换指定值(多列)(部分更新)
把表中 [符合条件的行的] 列名1字段中的查找内容全部修改为替换内容 [,列名2字段中的查找内容全部修改为替换内容]。
update 表名 set 列名1 = replace(列名1, '查找内容', '替换内容') [,列名2 = replace(列名2, '查找内容', '替换内容')] [where 条件];
(2)按照不同条件(批量)更新不同值
使用 if
把表中 [符合条件的行的] 列名1字段中符合条件1的内容修改为值1,否则修改为值2 [,列名2字段中符合条件2的内容修改为值3,否则修改为值4]。
update table 
set 
	列名1 = if(条件1,值1,值2),
    列名2 = if(条件2,值3,值4)
[where 条件];
使用 case when
把表中 [符合条件的行的] 列名1字段中符合条件1的内容修改为值1 [,符合条件2的修改为值2,...] [,列名2字段中符合条件21的内容修改为值21,符合条件22的修改为值22,...] 。
update table 
set 列名1 =
    case
        when 条件1 then 值1
        when 条件2 then 值2
        when 条件3 then 值3
        ...
    end,
    列名2 =
    case
        when 条件21 then 值21
        when 条件22 then 值22
        when 条件23 then 值23
        ...
    end
[where 条件];
三、实例
students 表 (id表示主键,name是姓名,score是平均成绩)
| id | name | score | 
|---|---|---|
| 1 | 李明 | 99 | 
| 2 | 张三 | 74 | 
| 3 | 孙华 | 59 | 
(1)根据条件更新值
把 students 表中 name 为张三的 score 字段的值全部修改为100。
#使用where update students set score = 100 where name = '张三';
| id | name | score | 
|---|---|---|
| 1 | 李明 | 99 | 
| 2 | 张三 | 100 | 
| 3 | 孙华 | 59 | 
把 students 表中 id 大于等于2的所有行中 score 中59的部分全部修改为0,name 中三的部分全部修改为四。
#使用replace update students set score = replace(score,59,0), name = replace(name,'三','四') where id >= 2;
注意:张三替换之后是张四,并不是只有字段等于三时才能替换。
| id | name | score | 
|---|---|---|
| 1 | 李明 | 99 | 
| 2 | 张四 | 74 | 
| 3 | 孙华 | 0 | 
(2)按照不同条件更新不同值
请把students表中score小于60的score字段全部改为0,否则改为100,name字段中的名字改为不及格,否则改为及格。
#批量更新多值 + if
update students 
set 
    score = if(score < 60,0,100),
    name = if(score < 60,'不及格','及格');
| id | name | score | 
|---|---|---|
| 1 | 及格 | 100 | 
| 2 | 及格 | 100 | 
| 3 | 不及格 | 0 | 
注意:更新的值要满足建表时的字段类型。比如score是int类型就不能更新为char类型。
请把students表中score小于60的score字段全部改为0,name字段中的名字改为不及格;score大于等于90的score字段全部改为2,name字段中的名字改为优秀;score大于等于60小于90的score字段全部改为1,name字段中的名字改为良好。
#批量更新多值 + case when
update students 
set 
    name = case
        when score < 60 then '不及格'
		when score >= 90 then '优秀'
        else '良好'
    end,
		score = case
        when score < 60 then 0
		when score >= 90 then 2
        else 1
    end;
注意:更新的时候是按照代码语句的先后顺序更新的。可以尝试先更新score后更新name,结果是不一样的。
| id | name | score | 
|---|---|---|
| 1 | 优秀 | 2 | 
| 2 | 良好 | 1 | 
| 3 | 不及格 | 0 | 
到此这篇关于MySQL实现数据更新的示例详解的文章就介绍到这了,更多相关MySQL数据更新内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!
