MYSQL - 根据条件更新新列的值

时间:2012-10-09 10:53:55

标签: mysql database sql-update

我有下表

+--------------+------------+------+-----+---------+-------+
| Field        | Type       | Null | Key | Default | Extra |
+--------------+------------+------+-----+---------+-------+
| image_id     | int(11)    | YES  |     | NULL    |       |
| image_status | bit(3)     | YES  |     | NULL    |       |
| image_result | varchar(4) | YES  |     | NULL    |       |
+--------------+------------+------+-----+---------+-------+

image_id和image_status列使用值填充。 image_result中的值都是NULL。

我想根据以下条件将以下值插入到image_result列中(我想更新表中的所有行) -

  • 如果image_status ='0'或image_status ='3'则image_result = '通过'
  • 如果image_status ='1'或image_status ='4'则image_result = '警告'
  • 如果image_status ='2'则image_result ='失败'

我该如何做?

3 个答案:

答案 0 :(得分:3)

UPDATE table 
SET image_result = CASE 
    WHEN image_status = 0 OR image_status = 3 THEN 'Pass' 
    WHEN image_status = 1 OR image_status = 4 THEN 'Warm' 
    ELSE 'Fail' 
END 

答案 1 :(得分:1)

UPDATE TableName
SET image_result = CASE 
                     WHEN image_status = '0' OR image_status = '3' THEN 'PASS'  
                     WHEN image_status = '1' OR image_status = '4' THEN 'Warn' 
                     WHEN image_status = '2' THEN 'Fail'
                   END
WHERE image_status IN('0', '1', '2', '3', '4'); 

答案 2 :(得分:0)

update <table> set image_result = 
Case when image_status = '0' OR image_status = '3' then 'Pass'
     when image_status = '1' OR image_status = '4' then 'Warn'
     when image_status = '2'                       then 'Fail'
End