我有一个包含一些用户数据的表,还有一个带有用户属性数据的表。属性总是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 User2USER_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"我在互联网上做了一些研究,显然这是通过支点实现的,但是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"结果在两条不同的线上。如果将结果按用户名分组,则图片数据始终为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;发布于 2015-11-15 09:58:46
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;https://stackoverflow.com/questions/33718280
复制相似问题