在mysql中加入数据透视表

时间:2018-03-19 11:04:24

标签: mysql sql join

如何使用pivotote table连接不同的表

我有4个表,比如

 users

 id  |  name |
 -------------
  1  |  abc  |
  2  |  ccc  |

user_profile

id   |  user_id | email |
-------------------------------
1    |    1     | abc@gmail.com 
2    |    2     | ccc@gmail.com

skills

id    |  skill_name  |
--------------------------
1    |   java       |
2    |   php        | 

user_skills

user_id   | skill_id   |
---------------------------
 1       |   1        |
 1       |   2        |
 2       |   1        |  

结果应为

 name  |  email       |  skills   |
 ----------------------------------
 abc   |abc@gmail.com | java, php |
 ccc   |ccc@gmail.com | java      |  

我可以加入多个表,但我有加入pivot的问题

我在下面尝试了查询

 SELECT users.name,user_profiles.email, group_concat(programs.name) 
 from users
 JOIN user_profiles on user_profiles.user_id = users.id
 LEFT JOIN user_skills on user_skills.user_id = users.id
 LEFT JOIN skills on user_skills.skill_id = skills.id
 GROUP BY users.id

任何人都可以帮我这个吗?谢谢

2 个答案:

答案 0 :(得分:1)

您需要GROUP_CONCAT来生成CSV技能列表:

SELECT
    u.name,
    up.email,
    GROUP_CONCAT(s.skill_name) AS skills
FROM users u
INNER JOIN user_profile up
    ON u.id = up.user_id
LEFT JOIN user_skills us
    ON u.id = us.user_id
INNER JOIN skills s
    ON us.skill_id = s.id
GROUP BY
    u.id, u.name, up.email;

Demo

请注意,我按用户的ID和名称进行分组,因为可能有两个用户碰巧具有相同的名称。请按照以下链接获取正在运行的SQLFiddle。

答案 1 :(得分:0)

您的查询应该有效。也许问题是引用programs而不是skills

select u.name, up.email, group_concat(s.name) 
from users u join
     user_profiles up
     on up.user_id = u.id left join
     user_skills us
     on us.user_id = u.id left join
     skills s
     on us.skill_id = s.id
group by u.name, up.email;