4

I have MySQL and the query is:

select name,re_type from myTable

I want to replace all values of type:

1 = student
2 = teacher 

So the result should be:

name    re_type
---------------
Ron     Student
Mac     Teacher

Not like:

name    re_type
---------------
Ron     1
Mac     2

Is it possible to make a query like that so I get the desired result in MySQL ?

3 Answers 3

9

You can use a CASE statement

SELECT name, CASE WHEN re_type = 1 THEN 'Student' WHEN re_type = 2 THEN 'Teacher' ELSE 'Donno' END AS re_type_text
FROM myTable 
Sign up to request clarification or add additional context in comments.

Comments

1

You can use a joint table that will store labels for your re_type like

re_type_id  re_type_label
1           student
2           teacher

And alter your query by :

select t.name,l.re_type_label
from myTable t
inner join labelsTable l
    on l.re_type_id = t.re_type

Comments

1

I think he wants to keep IDs on re_type field, and just decoding them when extracting.

You can use CASE WHEN or ELT(), MySql equivalent to Oracle's Decode(), like explained here

, but the Best Practice is to create an external table containing re_type and re_type_description fields, so if tomorrow you'll have new values, you don't have to change all your queries.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.