我是2个mysql表,第一个表Activity
将患者活动级别存储为整数,另一个表将每个整数与描述相映射。我正在尝试创建一个选择查询,它给出了患者活动的描述,而不是整数值。
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
我已经研究过使用mysql [CASE] [1],但这似乎不起作用。我还回顾了这两个stackoverflow问题[问题1] [2]和[问题2] [3]他们似乎并不是我想要的。任何帮助将不胜感激。
答案 0 :(得分:1)
以下代码使用您的映射表来显示正确的描述。选择subquery上的MYSQL文档。
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
答案 1 :(得分:1)
使用左连接的另一种方法:
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
使用MySQL,可能无法为每个具有映射值的列加入映射表一次。 (在MSSQL上,您可以使用unpivot/pivot
代替(example))。