2015-07-20 61 views
3

我有表,我想加入Mysql的JOIN選擇查詢與關鍵在一個字段和值在另一個領域

表用戶

id | name | age 
---------------- 
1 | Dave | 23 
2 | Dane | 65 
3 | Sam | 15 

表user_profile

user_id | profile_key | profile_value 
------------------------------------------------ 
    1  | prfle.about | This is about Dave bio 
    1  | prfle.cntry | Germany 
    2  | prfle.email | [email protected] 
    1  | prfle.email | [email protected] 
    3  | prfle.about | This something about Sam 
    2  | prfle.cntry | Canada 

我想選擇這兩個表爲

id | name | age | prfle.about    | prfle.email  | prfle.cntry 
------------------------------------------------------------------------- 
1 | Dave | 23 | This is about Dave bio | [email protected] | Germany 
2 | Dane | 65 | null     | [email protected] | Canada 
3 | Sam | 15 | This something about Sam | null    | null 

這是我的查詢

SELECT u.id, u.name, u.age, p.user_id, p.profile_key, p.profile_value 
FROM user as u 
LEFT JOIN user_profile as p 
ON u.id = p.user_id 

但是,當我執行它,我得到的東西像一個笛卡兒連接。

我會很高興,如果有人能幫助我

+0

號你喜歡的東西外,你可以使用下面的方法來生成數據透視表加入。 – Strawberry

回答

1

如果您profile_key值有限,那麼作爲

select 
u.*, 
max(case when up.profile_key = 'prfle.about' then up.profile_value end) as `prfle.about`, 
max(case when up.profile_key = 'prfle.cntry' then up.profile_value end) as `prfle.cntry`, 
max(case when up.profile_key = 'prfle.email' then up.profile_value end) as `prfle.email` 
from user u 
left join user_profile up on up.user_id = u.id 
group by u.id 
相關問題