所以我有三张桌子:
表Workers_projects存储哪个工作人员正在处理哪个项目(通过ID)
目标:
在某些情况下,一些工人将在同一个项目上工作。我想提出两个输出:
SQL选择第1列中的所有项目,并列出第2列中处理它的每个工作人员。
和
SQL选择第1列中的所有工作者,并列出第2列中工作人员正在处理的每个项目。
到目前为止我得到了什么:
SELECT p.name, GROUP_CONCAT(w.name)
FROM workers_projects as wp
LEFT JOIN projects as p ON wp.project_id=p.id
LEFT JOIN workers as w ON wp.worker_id=w.id
我做什么 - 它需要随机项目,然后列出所有工人.. 我对SQL很陌生,所以感谢任何帮助。
谢谢!
答案 0 :(得分:1)
您发布的代码看起来非常接近您想要的输出。 这就是你要追求的吗?
# Projects with workers
SELECT p.name AS project, GROUP_CONCAT(w.name SEPARATOR ', ') AS workers
FROM projects p
LEFT JOIN workers_projects wp ON (p.id = wp.project_id)
LEFT JOIN workers w ON (w.id = wp.worker_id)
GROUP BY p.id
# Workers with projects
SELECT w.name AS worker, GROUP_CONCAT(p.name SEPARATOR ', ') AS projects
FROM workers w
LEFT JOIN workers_projects wp ON (w.id = wp.worker_id)
LEFT JOIN projects p ON (p.id = wp.project_id)
GROUP BY w.id
如果您只想显示包含工作人员的项目,或者只显示包含项目的工作人员,则可以使用INNER JOIN
代替LEFT JOIN
。
以下是一个例子:
SELECT p.name AS project, GROUP_CONCAT(w.name SEPARATOR ', ') AS workers
FROM projects p
INNER JOIN workers_projects wp ON (p.id = wp.project_id)
INNER JOIN workers w ON (w.id = wp.worker_id)
GROUP BY p.id