下表是一个示例表结构。
我想写的查询类似于:
SELECT * FROM jobs LEFT JOIN assigned ON jobs.id = assigned.job_id;
但是,正如您可以看到,在作业100的情况下左连接将产生多个匹配,但上述查询将仅返回一个匹配。
是否可以将结果连接到左连接的逗号分隔字符串?
如果可能的话,更进一步的步骤是,是否可以用连接的逗号分隔字符串中的assigned.name列替换assigned.user_id。
用户
╔═══╦════════════╦═════════════╗
║ ║ id ║ name ║
╠═══╬════════════╬═════════════╣
║ 1 ║ 1 ║ Matt ║
║ 2 ║ 2 ║ Phil ║
║ 3 ║ 3 ║ Chris ║
╚═══╩════════════╩═════════════╝
作业
╔═══╦════════════╦═════════════╗
║ ║ id ║ name ║
╠═══╬════════════╬═════════════╣
║ 1 ║ 100 ║ Do this ║
║ 2 ║ 101 ║ Do that ║
║ 3 ║ 102 ║ And this ║
╚═══╩════════════╩═════════════╝
分配
╔═══╦════════════╦═════════════╗
║ ║ user_id ║ job_id ║
╠═══╬════════════╬═════════════╣
║ 1 ║ 1 ║ 100 ║
║ 2 ║ 2 ║ 100 ║
║ 3 ║ 1 ║ 101 ║
╚═══╩════════════╩═════════════╝
答案 0 :(得分:1)
SELECT jobs.id,
jobs.name,
GROUP_CONCAT( users.name order by users.name) as workersOnTheJob
FROM
jobs
LEFT JOIN assigned
ON jobs.id = assigned.job_id
LEFT JOIN users
on assigned.user_id = users.id
group by
jobs.id,
jobs.name