更新单个记录
UPDATE `table_name` SET `field1` = 'value1' WHERE `field2` = 'value2'
更新多个记录的同一个字段为同一个值
UPDATE `table_name` SET `field1` = 'value1' WHERE `field2` IN ('value2', 'value3')
更新多个记录的同一个字段为不同的值
mysql 并没有提供直接的方法来实现批量更新,但是可以用点小技巧来实现:
UPDATE `table_name` SET
`field1` = CASE `id`
WHEN 1 THEN 'value1'
WHEN 2 THEN 'value2'
END
WHERE `id` IN (1,2,3);
更新多个记录的多一个字段为不同的值
如果更新多个字段的话,在上面的基础上修改一下就可以了:
UPDATE `table_name` SET
`field1` = CASE `id`
WHEN 1 THEN 'value1'
WHEN 2 THEN 'value2'
END,
`field2` = CASE `id`
WHEN 1 THEN 'value3'
WHEN 2 THEN 'value4'
END,
WHERE `id` IN (1,2,3);
参考:
- https://www.awaimai.com/2103.html
- http://www.ghugo.com/update-multiple-rows-with-different-values-and-a-single-sql-query/
PS:个人博客原文:MySQL 批量更新、插入语句