将int值分配给特定字符串

时间:2013-08-05 12:59:09

标签: mysql

考虑以下简单的MySQL表:

| Answer           |
| ---------------- |
| Extremely likely |
| Likely           |
| Likely           |
| Not a chance     |
| Likely           |
| Potato           |
| Unlikely         |

我想从这个表中向SELECT写一个查询,其中将'极有可能'的任何出现替换为1,'可能'用2替换,'不太可能'用3和'不是'机会'与4。

不应转换所有其他答案。

结果将是:

| Answer |
| ------ |
| 1      |
| 2      |
| 2      |
| 4      |
| 2      |
| Potato |
| 3      |

这可以单独用SQL完成吗?


在回答了这个问题之后,我意识到我还需要在另一个字段具有特定值时才这样做。这是一张表:

| QuestionID | Answer           |
| ---------- | ---------------- |
| how_likely | Extremely likely |
| how_likely | Likely           |
| how_likely | Likely           |
| fave_veg   | Potato           |

我成功使用的查询是:

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`

2 个答案:

答案 0 :(得分:4)

SELECT CASE answer
         WHEN 'Extremely Likely' THEN 1
         WHEN 'Likely'           THEN 2
         WHEN 'Unlikely'         THEN 3
         WHEN 'Not a chance'     THEN 4
         ELSE answer
       END As new_answer
FROM   your_table

编辑:如果你有批次的[动态]替换,那么你可能会发现这种方法太难以维护。在这些情况下,您应该创建一个查找表,您可以执行OUTER JOIN到:

SELECT Coalesce(lookup_values.new_answer, your_table.answer) As new_answer
FROM   your_table
 LEFT
  JOIN lookup_values
    ON lookup_values.answer = your_table.answer

答案 1 :(得分:0)

REPLACE(REPLACE(REPLACE(REPLACE(Answer, 'Extremely likely', '1') , 'Likely', '2') , 'Unlikely', '3') , 'Not a chance', '4')