Mysql JOIN选择一个字段中的键和另一个字段中的值的查询

时间:2015-07-20 09:13:10

标签: mysql

我必须在桌子上试图加入

表用户

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

table user_profile

user_id | profile_key  | profile_value
------------------------------------------------
  1     | prfle.about  | This is about Dave bio
  1     | prfle.cntry  | Germany
  2     | prfle.email  | dane@somewhere.com
  1     | prfle.email  | dave@somewhere.com
  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   | dave@somewhere.com | Germany
 2 | Dane | 65   |    null                  | dane@somewhere.com | 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

但是当我执行它时,我会得到类似笛卡尔联合的东西。

如果有人能帮助我,我会很高兴

1 个答案:

答案 0 :(得分: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