'Show Result based on mapped tables

I've 2 mysql table, the first table Activity stores a patient activity level as an integer, another table maps each integer with a description. I am trying to create a select query that gives me the description for the patients activity instead of the integer value.

Activity Table
id|pid|bathing|cognition|housekeeping|dressing|feeding|meal
1 | 20|  4    |   4     |      2     |    6   |   8   |   4
2 | 40|  4    |   2     |      4     |    4   |   6   |   6  

Mapping Table
value|description
2    | Independent
4    | Minimal 
6    | Moderate
8    | Maximum

Desired Query Result

id|cid|bathing|cognition|housekeeping|dressing|feeding|meal
1 | 20|Minimal|Minimal  |Independent |Moderate|Maximum|Minimal

I've looked into using mysql [CASE][1] but that doesn't seem to work. I've also reviewed these two stackoverflow questions [Question1][2] and [Questions2][3] they didn't really seem to be what I was looking for.



Solution 1:[1]

The following code uses your mapping table to display the correct description. MYSQL documentation on select subquery.

Select id, pid,
(Select description from mapping where value=a.bathing) as 'bathing',
(Select description from mapping where value=a.cognition) as 'cognition',
(Select description from mapping where value=a.housekeeping) as 'housekeeping',
(Select description from mapping where value=a.dressing) as 'dressing',
(Select description from mapping where value=a.feeding) as 'feeding',
(Select description from mapping where value=a.meal) as 'meal'
From activity a

Solution 2:[2]

An alternative way using left joins:

select 
  id, 
  pid, 
  m1.description as bathing,
  m2.description as cognition,
  m3.description as housekeeping,
  m4.description as dressing,
  m5.description as feeding,
  m6.description as meal
from activity
left join mapping m1 on m1.value = bathing
left join mapping m2 on m2.value = cognition 
left join mapping m3 on m3.value = housekeeping 
left join mapping m4 on m4.value = dressing 
left join mapping m5 on m5.value = feeding 
left join mapping m6 on m6.value = meal 

Sample SQL Fiddle

With MySQL there's probably no way around joining the mapping table once for every column with a value to map. (On MSSQL you could have used unpivot/pivot instead (example)).

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2