Tuesday, 11 November 2014

MYSQL - Update values of new column based on condition

I have the following table
+--------------+------------+------+-----+---------+-------+
| 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 and image_status columns are populated with values. The values in image_result are all NULL.
I want to insert the following values into the image_result column based on the following conditions (I want to update all the rows in the table)-
  • if image_status = '0' OR image_status = '3' then image_result = 'Pass'
  • if image_status = '1' OR image_status = '4' then image_result = 'Warn'
  • if image_status = '2' then image_result = 'Fail'
How do I do the above?

Solution:
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 

0 comments:

Post a Comment