[英]MySQL Pivoting rows and columns
我有一个包含一些用户数据的表,还有一个包含用户属性数据的表。 属性始终为2,我知道它们的名称。 我需要一个查询来检索单个结构中的所有内容。 但是,我无法更改数据库架构。
这是数据库的简化版本:
用户
+-------------------+--------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+-------------------+--------------+------+-----+---------+-------+
| username | varchar(64) | NO | PRI | NULL | |
| name | varchar(100) | YES | | NULL | |
+-------------------+--------------+------+-----+---------+-------+
USER_PROPERTIES
+-----------+--------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+-----------+--------------+------+-----+---------+-------+
| username | varchar(64) | NO | PRI | NULL | |
| propName | varchar(100) | NO | PRI | NULL | |
| propValue | text | NO | | NULL | |
+-----------+--------------+------+-----+---------+-------+
因此,例如,具有以下数据:
用户
username name
1 User1
2 User2
USER_PROPERTIES
username propName propValue
1 status "At work"
1 picture "pict1.jpg"
2 status "Busy"
2 picture "pict2.jpg"
我需要以下结果:
username name STATUS PICTURE
1 User1 "At work" "pict1.jpg"
2 User2 "Busy" "pict2.jpg"
我在Internet上做了一些研究,显然这是通过PIVOT实现的,但是MySQL不包含此功能。 通过遵循以下答案: MySQL数据透视表 ,我可以设法做到这一点:
select ou.username,
case when (oup.propName='status') then oup.propValue end as 'STATUS',
case when (oup.propName='picture') then oup.propValue end as 'PICTURE'
from User ou, User_Properties oup
where ou.username = oup.username;
username name STATUS PICTURE
1 User1 "At work" null
1 User1 null "pict1.jpg"
2 User2 "Busy" null
2 User2 null "pict2.jpg"
结果在两个不同的行中。 如果按用户名对结果进行分组,则将PICTURE数据始终为null:
select ou.username,
case when (oup.propName='status') then oup.propValue end as 'STATUS',
case when (oup.propName='picture') then oup.propValue end as 'PICTURE'
from User ou, User_Properties oup
where ou.username = oup.username
group by oup.username;
username name STATUS PICTURE
1 User1 "At work" null
2 User2 "Busy" null
我想念什么? 谢谢。
编辑: https : //stackoverflow.com/users/1529673/strawberry提供了解决方案:
select ou.username,
MAX(case when (oup.propName='status') then oup.propValue end) as 'STATUS',
MAX(case when (oup.propName='picture') then oup.propValue end) as 'PICTURE'
from User ou, User_Properties oup
where ou.username = oup.username;
https://stackoverflow.com/users/1529673/strawberry提供了解决方案:
select ou.username,
MAX(case when oup.propName='status' then oup.propValue end) as 'STATUS',
MAX(case when oup.propName='picture' then oup.propValue end) as 'PICTURE'
from User ou
Join User_Properties oup
On ou.username = oup.username;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.