MySQL根据同一列中的值更新单个列上的多个行

时间:2011-08-31 18:29:33

标签: mysql entity-attribute-value

我的表格如下所示:

ID     Key     Value     Order
1      gender  m         0
2      gender  f         0

34     age     10        0
35     age     80        0

要更新这些行,我必须使用以下内容:

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'

有没有办法将此合并到一个更新语句中,而不使用ID(不保证是相同的),例如(即使这不起作用)......

UPDATE `DemoGroup` 
SET `value`= CASE `value`
    WHEN 'm' THEN 'male',
    WHEN 'f' THEN 'female' END 
WHERE `value` = 'm' OR `value` = 'f'

如果我能弄清楚如何为每一行设置Order字段,那么更多的奖励(但不是nesseary)......

2 个答案:

答案 0 :(得分:14)

您可能不仅应根据value的值更新值,还应根据key的值更新值,否则当键值为'shirt-size时,您可以将'm'更新为'male' ”。

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');

答案 1 :(得分:0)

MySQL确实有一个案例功能。尝试:

UPDATE DemoGroup SET `value` = 
CASE `value` WHEN 'm' THEN 'male'
WHEN 'f' THEN 'female'
WHEN '10' THEN '10-19'
WHEN '80' THEN '80-89' END;