2015-09-26 58 views
3

我有一個要求將所有與會話相關聯的教育工作者作爲連接列表返回,但要在連接內部完成(不要問 - 我知道有多種方法可以實現,但我是與不接受這些方法的庫一起工作;-))MySQL聯結表連接

我有一個sessions表,session_idsession_name

| session_id | session_name | 
+------------+--------------+ 
| 1   | Swimming  | 
| 2   | Chess  | 

我有一個session_educators表基本上是一個結表session_idcontact_id

| session_id | contact_id | 
+------------+------------+ 
| 1   | 1   | 
| 1   | 2   | 
| 2   | 3   | 
| 2   | 4   | 

我有一個contactscontact_idfull_name

| contact_id | full_name | 
+------------+--------------+ 
| 1   | Fred Bloggs | 
| 2   | Mary Bloggs | 
| 3   | Mark Smith | 
| 4   | Shelly Smith | 

到目前爲止,這似乎是最接近我來:

SELECT 
    sessions.session_id, 
    sessions.name, 
    educators.names 
FROM 
    `sessions` 
LEFT JOIN 
    (
     SELECT 
      GROUP_CONCAT(contacts.full_name SEPARATOR ', ') as names 
     FROM 
      `contacts` 
     WHERE 
      contact_id 
     IN 
      (
       SELECT 
        contact_id 
       FROM 
        session_educator 
       WHERE 
        session_educator.session_id = sessions.session_id 
      ) 
    ) `educators` 
USING 
    (`session_id`) 

但我真的在摸索試圖找出它的黑暗,任何人都可以幫忙嗎?

我想要什麼,因爲你也許可以從查詢來講,是這樣一個結果:

| session_id | session_name | educators    | 
+------------+--------------+--------------------------+ 
| 1   | Swimming  | Fred Bloggs, Mary Bloggs | 
| 2   | Chess  | Mark Smith, Shelly Smith | 

任何幫助,不勝感激 - 哪怕它只是說,它不能做!

回答

1

我相信你正在做這一切有點複雜得多,需要的(除非我已經錯過了你的要求,這是我知道有多少痛苦庫?可以...)

這爲我工作:

SELECT 
    session_id, 
    session_name, 
    (
     SELECT 
      GROUP_CONCAT(full_name SEPARATOR ', ') as names 
     FROM 
      contacts c, 
      session_educators se 
     WHERE 
      c.contact_id = se.contact_id 
     AND 
      se.session_id = s.session_id 
    ) 
FROM 
    sessions s 
; 
+0

也謝謝你,也是一種享受。我這樣做愛stackoverflow :-) – annoyingmouse

2

你不應該爲此需要子查詢。這是幾個連接和聚合:

select s.session_id, s.session_name, 
     group_concat(e.name separator ', ') as educators 
from sessions s left join 
    session_educators se 
    on se.session_id = s.session_id left join 
    educators e 
    on e.educator_id = se.educator_id 
group by s.session_id; 
+0

謝謝你,工作一種享受! – annoyingmouse