更新多条 单列
记录 语法:
update tablename set
myfield = case id
when 1 then 'value1'
when 2 then 'value2'
...
when n then 'valuen'
end
where id in (1,2,...,n);
注:myfield是是你需要更改的字段名称,如果id等于1就把value1的赋给这条记录的这个列上,后边依次往下走。
现有学生表 name:姓名,class:班级
示例:修改student表,更改所有人的班级,id为1就改为高二一班,id为2就改为高二二班,以此类推。
sql:
update student set
class = case id
when 1 then '高二一班'
when 2 then '高二二班'
when 3 then '高二三班'
when 4 then '高二四班'
when 5 then '高二五班'
end
where id in (1,2,3,4,5);
执行成功,这是修改之后的数据
class = case id
when 1 then '高二一班'
when 2 then '高二二班'
when 3 then '高二三班'
when 4 then '高二四班'
when 5 then '高二五班'
end
这一段我的理解是:如果id 等于1 就把'高二一班' 给赋值到这一条记录的class字段上,后边的以此类推。
更新多条 多列
记录 语法:
update tablename set
myfield1 = case id
when 1 then 'value1'
when 2 then 'value2'
...
when n then 'valuen'
end
myfield2 = case id
when 1 then 'value1'
when 2 then 'value2'
...
when n then 'valuen'
end
...
myfieldn = case id
when 1 then 'value1'
when 2 then 'value2'
...
when n then 'valuen'
end
where id in (1,2,...,n);
注:myfield是你需要更改的各个字段名称,只是把修改单列变成了多列,这里就不写示例了。
更新多表
记录 语法:
update t1,t2,tn set t1.field1=value1,tn.fieldn=valuen [where condition];
表信息
示例:把学生表id为1的名称修改为海王,和他关联的总分和平均都改为0
sql:
update student,score set
student.name = '海王',
score.fraction='0',
score.average=0
where
student.id = score.sid and student.id = 1;
执行成功,这是修改之后的数据
注:sql语句中的第一个where条件student.id = score.sid,在这里是两表关联
不写关联条件的写法,(在这里用了别名)
sql:
update student as s1,score as s2 set
s1.name='海娃',
s2.fraction='60'
where s1.id=1 and s2.sid = 1;
执行成功,这是修改之后的数据
注:where条件中不关联,那就要针对每一个表写条件,如果不写的话后果很严重(虽然我也不知道会发生什么);