时间:2021-06-13 08:45:09 | 栏目:Mysql | 点击:次
在处理批量更新某些数据的时候,如果跟你更新的字段的值都一样,比如某个状态都更新为某个固定值,
如果要更新的字段的值是不固定的,用下面的update case when where 这种方式就更方便了
UPDATE tablename set a1= CASE userid WHEN 1 THEN a1+5 WHEN 2 THEN a1+2 END, a2= CASE userid WHEN 1 THEN a2-5 WHEN 2 THEN a2-2 END where userid in (1,2)
用update case when 更新的时候一定要带上 where 条件,否则会更新整张表,后果很严重。
补充:Mysql update && case when 联合使用 批量更新
直接码sql:
UPDATE t_report SET room = CONCAT_WS( '-', SUBSTRING_INDEX(room, '-', 1) , CASE SUBSTRING_INDEX(room, '-', -1) WHEN 'N01' THEN 'N02' WHEN 'N02' THEN 'N01' WHEN 'N03' THEN 'N11' WHEN 'N04' THEN 'N10' WHEN 'N05' THEN 'N09' WHEN 'N06' THEN 'N08' WHEN 'N07' THEN 'N07' WHEN 'N08' THEN 'N06' WHEN 'N09' THEN 'N05' WHEN 'N10' THEN 'N03' END ) WHERE rid IN ( SELECT rid FROM t_report WHERE rdate = '190306' AND ordinal BETWEEN '23' AND '32' )