我有一个包含一些用户数据的表,第二个包含用户属性数据的表。这些属性总是 2,而且我知道它们的名字。我需要一个查询来检索单个结构中的所有内容。但是,我无法更改数据库架构。
这是我的数据库的简化版本:
用户
+-------------------+--------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+-------------------+--------------+------+-----+---------+-------+
| username | varchar(64) | NO | PRI | NULL | |
| name | varchar(100) | YES | | NULL | |
+-------------------+--------------+------+-----+---------+-------+
用户属性
+-----------+--------------+------+-----+---------+-------+
| 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
用户属性
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"
我在互联网上做了一些研究,显然这是通过PIVOT实现的,但MySQL不包含此功能。按照此处的答案:MySQL pivot table ,我可以设法得到这个:
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"
结果分为两行。如果我按用户名对结果进行分组,我得到的图片数据始终为空:
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;
关于MySQL 旋转行和列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33718280/