Consider the following simple MySQL table:
| Answer |
| ---------------- |
| Extremely likely |
| Likely |
| Likely |
| Not a chance |
| Likely |
| Potato |
| Unlikely |
I would like to write a query to SELECT from this table, which replaces any occurrences of 'Extremely likely' with 1, 'Likely' with 2, 'Unlikely' with 3 and 'Not a chance' with 4.
All other answers should not be converted.
So the result would be:
| Answer |
| ------ |
| 1 |
| 2 |
| 2 |
| 4 |
| 2 |
| Potato |
| 3 |
Can this be done with SQL alone?
After this question was answered I realised I also needed to only do this when another field had a particular value. Here is such a table:
| QuestionID | Answer |
| ---------- | ---------------- |
| how_likely | Extremely likely |
| how_likely | Likely |
| how_likely | Likely |
| fave_veg | Potato |
The query I successfully used for this was:
SELECT QuestionID,
IF(
QuestionID = 'how_likely',
CASE Answer
WHEN 'Extremely likely' THEN 1
WHEN 'Likely' THEN 2
WHEN 'Unlikely' THEN 3
WHEN 'Not a chance' THEN 4
END,
Answer
) AS Answer
FROM `answers`