首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >基于映射表显示结果

基于映射表显示结果
EN

Stack Overflow用户
提问于 2015-03-17 23:59:11
回答 2查看 59关注 0票数 0

我有两个mysql表,第一个表Activity将病人活动级别存储为整数,另一个表用描述映射每个整数。我正在尝试创建一个select查询,为我提供对病人活动的描述,而不是整数值。

代码语言:javascript
复制
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 --它们似乎并不是我想要的。

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2015-03-18 00:17:27

下面的代码使用映射表显示正确的描述。关于选择子查询的MYSQL文档。

代码语言:javascript
复制
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
EN

Stack Overflow用户

发布于 2015-03-18 00:38:02

另一种使用左联接的方法:

代码语言:javascript
复制
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 (示例))。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/29111903

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档