[英]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.