Heim  >  Artikel  >  Datenbank  >  mysql批量更新

mysql批量更新

WBOY
WBOYOriginal
2016-06-07 15:33:441114Durchsuche

在处理大数据时,有时候会经常遇到大量的数据需要更新或插入,如何进行优化。 批量插入其实挺简单,只要用insert into 后面跟多个VALUES集合即可。那么,批量更新有哪些方法呢? 一、使用insert into ... on duplicate key update insert into table (aa,bb,

        在处理大数据时,有时候会经常遇到大量的数据需要更新或插入,如何进行优化。 批量插入其实挺简单,只要用insert into 后面跟多个VALUES集合即可。那么,批量更新有哪些方法呢?


一、使用insert into ... on duplicate key update

insert into table (aa,bb,cc) values(xx,xx,xx),(oo,oo,oo) on duplicate key update aa=values(aa),bb=values(bb),cc=values(bb)+values(cc)

这种方法在插入前会判断主键或唯一值存在,values后可跟多条记录。如果不存在则批量插入;如果存在则更新操作,更新规则可以自定义,cc=values(bb)+values(cc)


二、使用replace into tab (),(),..

replace into table (aa,bb,cc) values(xxx,xxx,xxx),(ooo,ooo,ooo),(ccc,ccc,ccc)

        该方式表是要有唯一主键的。原理跟A差不多。判断主键,存在即更新,不存在则插入。 如果只更新其中1、2个字段的时候,不要用这个方法,否则会将其他的字段置空,或者执行前将values值填写完整。

        不过该方法有个坑,对于配置有主从服务器的时候,会导致从库的自增主键与主库的自增主键无法保持一致。详细链接: http://blog.xupeng.me/2013/10/11/mysql-replace-into-trap/


注:replace into 和insert into on duplicate key update的不同

 a、replace into 操作本质是对重复的记录先delete 后insert,如果更新的字段不全会将缺失的字段置为缺省值。

 b、insert into 则是只update重复记录,不会改变其它字段。


三、创建临时表,先更新临时表,然后从临时表中update

create temporary table tmp(id int(4) primary key,dr varchar(50));
insert into tmp values  (0,'gone'), (1,'xx'),...(m,'yy');
update test_tbl, tmp set test_tbl.dr=tmp.dr where test_tbl.id=tmp.id;


Stellungnahme:
Der Inhalt dieses Artikels wird freiwillig von Internetnutzern beigesteuert und das Urheberrecht liegt beim ursprünglichen Autor. Diese Website übernimmt keine entsprechende rechtliche Verantwortung. Wenn Sie Inhalte finden, bei denen der Verdacht eines Plagiats oder einer Rechtsverletzung besteht, wenden Sie sich bitte an admin@php.cn
Vorheriger Artikel:MySQL函数集锦Nächster Artikel:Mysql Left Join Where On