考慮下面這個簡單的MySQL表:分配INT值,以特定字符串
| Answer |
| ---------------- |
| Extremely likely |
| Likely |
| Likely |
| Not a chance |
| Likely |
| Potato |
| Unlikely |
我想編寫一個查詢從該表中,這取代「極有可能」的任何出現與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`
查找表是不是一個壞主意。我會研究一下,謝謝。 – tomturton