MySQL联结表串联

时间:2015-09-26 14:12:47

标签: 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          |

我有contacts表格contact_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 |

任何帮助都非常感激 - 即使只是说它无法完成!

2 个答案:

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

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