当前位置: 移动技术网 > IT编程>数据库>Mysql > Mysql Update批量更新的几种方式

Mysql Update批量更新的几种方式

2019年03月18日  | 移动技术网IT编程  | 我要评论

通常情况下,我们会使用以下sql语句来更新字段值:

update mytable set myfield='value' where other_field='other_value';

但是,如果你想更新多行数据,并且每行记录的各字段值都是各不一样,你会怎么办呢?刚开始你可能会想到使用循环执行多条update语句的方式,就像以下的python程序示例:

for x in xrange(10):
  sql = ''' update mytable set myfield='value' where other_field='other_value'; '''

这种方法并没有什么任何错误,并且代码简单易懂,但是在循环语句中执行了不止一次sql查询,在做系统优化的时候,我们总是想尽可能的减少数据库查询的次数,以减少资源占用,同时可以提高系统速度。幸运的是,还有更好的解决方案,只不过sql语句稍微复杂点,但是只需执行一次查询即可,语法如下:

update mytable
  set myfield = case other_field
    when 1 then 'value'
    when 2 then 'value'
    when 3 then 'value'
  end
where id in (1,2,3)

这样的sql语句是很容易理解的,也就是用到了很多编程语言都有的关键字 case,根据id字段值来进行不同分支的当型判断,

如果你需要更新一行记录的多个字段,可以用以下sql语句:

update categories
  set display_order = case id
    when 1 then 3
    when 2 then 4
    when 3 then 5
  end,
  title = case id
    when 1 then 'new title 1'
    when 2 then 'new title 2'
    when 3 then 'new title 3'
  end
where id in (1,2,3)

以上方案大大减少了数据库的查询操作次数,大大节约了系统资源

不过这个有个缺点 : 要注意的问题是sql语句的长度,需要考虑程序运行环境所支持的字符串长度,当然这也可以更新mysql的设置来扩展。

当然python这么强大的语言还给我们提供了executemany 这么强大的方法 ,它不仅可以插入数据 当然也可以用于更新数据 作为一个经常搞事情的人 这些东西要经常相互用下 才可以对比出结果

update_sql = ''' update mayi_order_image 
set order_city = %s
where user_ip = %s and dt = %s and id = %s 
 and user_ip is not null and (order_city is null or order_city = '' )
 '''
pp = []
for x in xrange(len(result)):
  ip = result[x][0]
  id_ = result[x][1]
  add = dbip.lookup(str(ip))
  adds = add.split('\t')
  address = str(adds[0]) + ','+str(adds[1] )+ ','+ str(adds[2])
  pp.append((address,ip,end,id_))
  if x%5000 == 0:
    savelog_many(update_sql,pp)
    pp = []
savelog_many(update_sql,pp)

是不是这个更方便一些 但是吗 速度 问题 我感觉可以和第二种结合一下对比一下会更好呢

总结

以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,谢谢大家对移动技术网的支持。如果你想了解更多相关内容请查看下面相关链接

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网