mysql将同一列值改为一致,MySQL根据同一列中的值更新同一列上的多行

I have a table that looks like the following:

ID Key Value Order

1 gender m 0

2 gender f 0

34 age 10 0

35 age 80 0

To update these rows I have to use the following:

UPDATE `DemoGroup` SET `value` = 'male' WHERE `value` = 'm'

UPDATE `DemoGroup` SET `value` = 'female' WHERE `value` = 'f'

UPDATE `DemoGroup` SET `value` = '10-19' WHERE `value` = '10'

UPDATE `DemoGroup` SET `value` = '80-89' WHERE `value` = '80'

Is there a way to consolidate this into one update statement, without using the ID (which is not guaranteed to be the same), such as (even though this won't work)...

UPDATE `DemoGroup`

SET `value`= CASE `value`

WHEN 'm' THEN 'male',

WHEN 'f' THEN 'female' END

WHERE `value` = 'm' OR `value` = 'f'

Even more of a bonus (but not nessesary) is if I could figure out how to set the Order field as well for each row...

解决方案

You should probably update the values based not only on the value of value but on the value of key, otherwise you could update 'm' to 'male' when key is 'shirt-size'.

UPDATE `DemoGroup`

SET `value` = CASE

WHEN (`key`, `value`) = ('gender', 'm') THEN 'male'

WHEN (`key`, `value`) = ('gender', 'f') THEN 'female'

WHEN (`key`, `value`) = ('age', '10') THEN '10-19'

WHEN (`key`, `value`) = ('age', '80') THEN '80-89'

ELSE `value` -- no-op for other values

END

WHERE `key` IN ('gender','age');

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值