SQL连接表2中的表和连接名称

时间:2017-07-01 10:25:58

标签: mysql sql

在Mysql 5.5中我有三个表:

雇员

ID | firstname | lastname
-------------------------
1  | John      | Doe
2  | Henry     | Fonda

employee_projects

ID | employee_id | project_id
------------------------------
1  | 1         | 1
2  | 1         | 2
3  | 2         | 3

项目

ID | name 
----------------------
1  | house   
2  | cottage 
3  | castle   

如何通过emloyee_project加入员工与我得到的项目结果:

ID | firstname | lastname | projects
-------------------------------------
1  | John      | Doe      | house, cottage
2  | Henry     | Fonda    | castle

2 个答案:

答案 0 :(得分:1)

您可以使用MySQL的group_concat

select  e.id
,       e.firstname
,       e.lastname
,       group_concat(p.name) as projects
from    employee e
left join
        employee_projects ep
on      e.id = ep.employee_id
left join
        projects p
on      ep.project_id = p.id
group by
        e.id
,       e.firstname
,       e.lastname

答案 1 :(得分:1)

您可以将这些表连接在一起,并使用group_concat将行聚合为csv值。

select e.*, t.projects
from employee e 
left join (
    select ep.employee_id, group_concat(p.name) as projects
    from employee_projects ep
    join projects p on ep.project_id = p.id
    group by ep.employee_id
    ) t on e.id = t.employee_id;