2015-02-11 82 views
0

我想加入MySQL表上的多列。我無法弄清楚如何將多個列檢索到單個行中,因此我可以在我的頁面上顯示一行。在MySQL表上加入多列

表:employee_timesheet

id employee_id service_area_name sign_off_1 sign_off_2 sign_off_3 created_date   status  last_updated 
1  2    London    Rom   Director NULL   2015-02-11 17:22:44 Submitted 2015-02-11 17:22:44 

表(空):employees_timesheet_sign_off_team_leaders

id employee_id timesheet_id sign_off_key team_leader_id 

表:employees_timesheet_sign_off_roms

id employee_id timesheet_id rom_id sign_off_key 
1  2    1    4   sign_off_1 
2  2    1    5   sign_off_1 

表:team_leaders

id first_name last_name email     reports_to status date_added    last_updated 
2  Bob   Test   [email protected]  4    Active 2015-02-03 12:50:25  2015-02-03 13:28:56 

表:ROM的

id first_name last_name email       status date_added    last_updated 
4  Bill   Gates  [email protected]  Active 2015-02-03 13:14:07  2015-02-03 13:28:40 
5  Ben   Morris  [email protected] Active 2015-02-11 17:35:43  NULL 

我需要加入上面的表,得到以下結果:

ID: 1 
Team Leader: (null) 
Rom: Bill Gates,Ben Morris 
Date: 2015-02-11 17:22:44 

這將是非常感謝,如果有人可以幫助這一點。

在此先感謝。

+0

嗨,我試過這個:http://pastebin.com/umDunz22 – V4n1ll4 2015-02-11 18:13:01

回答

2

對於您的用例,您需要使用GROUP_CONCAT功能:http://www.percona.com/blog/2013/10/22/the-power-of-mysqls-group_concat/。該查詢將如下所示:

SELECT et.id, CONCAT(l.first_name, ' ', l.last_name) 'team_leader', GROUP_CONCAT(DISTINCT CONCAT(r.first_name, ' ', r.last_name)), et.last_updated 
FROM employee_timesheet et 
INNER JOIN employees_timesheet_sign_off_roms etr ON et.id = etr.timesheet_id 
INNER JOIN roms r ON etr.rom_id = r.id 
LEFT JOIN employees_timesheet_sign_off_team_leaders etl ON et.id = etl.timesheet_id 
LEFT JOIN team_leaders l ON etl.team_leader_id = l.id 
GROUP BY et.id, team_leader, et.last_updated 
+0

謝謝,第一次工作:) – V4n1ll4 2015-02-11 18:43:23