SQL查询问题
考虑两个表。Employee和Project。Employee表有eid、ename等字段。Project表有pid、pname等字段。现在,由于一个员工可以在多个项目上工作,并且一个项目可以由多个员工完成,因此,很明显,这两个表之间存在多对多关系。打破多对多关系,并创建一个名为Assignment的新表,其中包含eid和pid作为外键。
问题是,我想找出那些在超过 1 个项目中相互合作过的员工对。例如,如果员工 A 和员工 B 在多个项目中相互合作过,那么他们就有资格进行上述查询结果。
请让我知道对上述问题的查询是什么。
Consider two table.Employee and Project.Employee table has fields like eid,ename.Project table has fields like pid,pname.Now,since an employee can work on many projects and a project can be done by many employees, therefore,as evident,there is a many to many relationship b/w the two tables.Break the many to many,and create a new table called Assignment which consists as foreign keys the eid and pid.
Here is the question, I Want to find out those employee pairs who have worked with each other in more than 1 project.For example if emp A and emp B have worked with each other on more than one project then they qualify for the above query result.
Kindly let me know what will be the query for the mentioned problem.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
这是一个非常常见且简单的解决方案:
此查询执行连接,将
Assignment
表中的行与同一表中具有相同项目和不同员工的其他行进行匹配。我们使用<
来比较员工 ID,这样我们就不会得到重复的配对。然后我们使用 GROUP BY 来确保每对员工只有一行。
HAVING
子句仅选择那些具有多行的组,这些组是一起处理多个项目的员工对。Here's a pretty common and straightforward solution:
This query does a join to match rows in the
Assignment
table to other rows in the same table with the same project and a different employee. We use<
to compare the employee id's so we don't get duplicate pairings.Then we use
GROUP BY
to make sure there's only one row for each pair of employees.The
HAVING
clause picks only those groups that have multiple rows, which are the pairs of employees who have worked on multiple projects together.这可以帮助你吗?
This can help you?
这就是我的写法,与 Bill 所写的非常相似,不同之处在于对不同项目进行计数,以防关系表中 (emp_id, prj_id) 没有唯一约束:
如果关系表还存储角色( dev、lead、q&a 等)是项目中人员的,同一对(emp_id、prj_id)在关系表中可能有多个条目。
这也会检索名称:
This is how I would write it, very similar to what Bill wrote with the difference being on counting the distinct projects in case there is no unique constrain on (emp_id, prj_id) in the relation table:
If the relation table also stores the role(dev, lead, q&a etc.) of the person in the project, it is possible to have multiple entries in the relation table for the same (emp_id, prj_id) pair.
This retrieves the names as well: