在SQL中映射值选择?

时间:2016-07-25 12:08:00

标签: mysql sql

我有一张桌子,为简单起见,请将其称为Plant, 有三列:idnamecategory
这是最简化的例子,所以请不要担心规范化......

+-------+--------+------------+
| id    | name   | category   |
+-------+--------+------------+
| 1     | orange | fruits     |
| 2     | banana | fruits     |
| 3     | tomato | vegetables |
| 4     | kaokao | NULL       |
+-------+--------+------------+

如果想要一个返回的查询:

  • ' Fruit Plant'而不是' fruits'
  • ' Vegetable Plant'而不是' vegetables'
  • ' unknown'而不是NULL s

所以回报应该是:

+-------+--------+-----------------+
| id    | name   | category        |
+-------+--------+-----------------+
| 1     | orange | Fruit Plant     |
| 2     | banana | Fruit Plant     |
| 3     | tomato | Vegetable Plant |
| 4     | kaokao | unknown         |
+-------+--------+-----------------+

如何为选择值执行此映射?

我正在使用mysql,如果这可能在mysql中有一个特殊的IF关键字/函数

3 个答案:

答案 0 :(得分:19)

您可以使用case表达式:

select
    id,
    name,
    case 
        when category = 'fruits' then 'Fruit Plant'
        when category = 'vegetables' then 'Vegetable Plant'
        when category is null then 'unknown'
    end as category
from Plant

答案 1 :(得分:3)

使用case函数(带else语句):

SELECT id, name, 
CASE category
 WHEN 'vegetables' THEN 'Vegetable Plant'
 WHEN 'fruits' THEN 'Fruit Plant'
 WHEN IS NULL THEN 'unknown'
 ELSE 'default values'
END
FROM Plant

答案 2 :(得分:0)

试一试:

SELECT
  `id`,
  `name`,
  CASE
    WHEN `category` = 'fruits' THEN 'Fruit Plant'
    WHEN `category` = 'vegetables' THEN 'Vegetable Plant'
    WHEN `category` = NULL THEN 'unknown'
    ELSE `category`
  END 
  AS `category`
FROM `Plant`