在SQL中映射值选择?

Ash*_*hir 10 mysql sql

我有一个表,让我们为简单起见称之为Plant,有三列:id,name,category.
这是最简化的例子,所以请不要担心规范化......

+-------+--------+------------+
| id    | name   | category   |
+-------+--------+------------+
| 1     | orange | fruits     |
| 2     | banana | fruits     |
| 3     | tomato | vegetables |
| 4     | kaokao | NULL       |
+-------+--------+------------+
Run Code Online (Sandbox Code Playgroud)

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

  • ' Fruit Plant'而不是' fruits'
  • ' Vegetable Plant'而不是' vegetables'
  • ' unknown'而不是NULLs

所以回报应该是:

+-------+--------+-----------------+
| id    | name   | category        |
+-------+--------+-----------------+
| 1     | orange | Fruit Plant     |
| 2     | banana | Fruit Plant     |
| 3     | tomato | Vegetable Plant |
| 4     | kaokao | unknown         |
+-------+--------+-----------------+
Run Code Online (Sandbox Code Playgroud)

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

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

And*_*yev 23

你可以使用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
Run Code Online (Sandbox Code Playgroud)

  • @AshrafBashir...使用`else`. (2认同)

Gra*_*ace 5

使用 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
Run Code Online (Sandbox Code Playgroud)