Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mapping values in SQL select?

Tags:

sql

mysql

I have a table, lets for simplicity call it Plant, with three columns: id, name, category.
This the most simplified example, so please do not worry about normalization ...

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

If want to have a query which returns:

  • 'Fruit Plant' instead of 'fruits'
  • 'Vegetable Plant' instead of 'vegetables'
  • 'unknown' instead of NULLs

So the return should be:

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

How can I do this mapping for select values ?

I am using mysql, if this may have a special IF keyword/function in mysql

like image 925
Ashraf Bashir Avatar asked Jul 25 '16 12:07

Ashraf Bashir


People also ask

What is mapping table in SQL?

Table mapping represents copying data from an external source (a CSV file or an SQL table) into the selected table at the column level. It allows transferring data from an existing source to multiple columns of the selected target table in one go, by using mapping dialog.

What Is column mapping in SQL?

Column mapping for SQL (SQL code) For each Column, ACS generates a column definition in the create table instruction created for the owning Table. If the Column's Can Be Null property is selected, it is generated as NULL. If the Column's Can Be Null property is not selected, it is generated as NOT NULL.


1 Answers

You can use case expression:

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 
like image 67
Andrey Korneyev Avatar answered Sep 19 '22 03:09

Andrey Korneyev