update带子查询更新

现在要做一下数据移植,需要更新相关的数据,需要在mysql中更新时不能将更新的表作为查询的表。
总结一下:
一:单表更新时
例如: update customer set category = 1 WHERE  deleteflag = 0 and name = '22';
注意不要子查询,mysql是不允许的。
二:带子查询的复杂更新
如:
update tb a,
(select  time,name
from tt )b
set time4=b.col
where a.name=b.name and a.time1=b.time;

注意点:
1、update 时,更新的表不能在set和where中用于子查询;
2、update 时,可以对多个表进行更新(sqlserver不行);
         如:update ta a,tb b set a.Bid=b.id ,b.Aid=a.id; 
3、update 后面可以做任意的查询,这个作用等同于from;

参考的文章:感谢原创,弄了半天才弄出来,看到这里,豁然开朗。
http://blog.csdn.net/xys_777/article/details/5793565

原需求:需要将info_stu_train_info的grade字段设成info_person_info中学号的前四位,两表根据personId关联,语句如下:
update info_stu_train_info t,(select left(perNum,4) as grade,personId from info_person_info where perNum is not null and perNum like '20%') as i set t.grade=i.grade
where t.personId=i.personId;

猜你喜欢

转载自weitao0912-163-com.iteye.com/blog/2150880