我有两个mysql表,第一个表Activity将病人活动级别存储为整数,另一个表用描述映射每个整数。我正在尝试创建一个select查询,为我提供对病人活动的描述,而不是整数值。
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的情况,但这似乎不起作用。我还回顾了这两个堆叠溢出问题-- Question1和Questions2 --它们似乎并不是我想要的。
发布于 2015-03-18 00:17:27
下面的代码使用映射表显示正确的描述。关于选择子查询的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发布于 2015-03-18 00:38:02
另一种使用左联接的方法:
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 示例SQL Fiddle
使用MySQL,对于每个要映射值的列,可能都无法绕过加入映射表一次。(在MSSQL上,您可以使用unpivot/pivot (示例))。
https://stackoverflow.com/questions/29111903
复制相似问题