我做了一些挖掘,无法安排在我的脑海里......我的问题是找到同一个项目中的员工和经理?我有两个表,他们是员工和项目。他们喜欢;
*Employee*
----------
employee_id (PK)
name
manager_id (FK) ref employee_id in same table which is employee_id.
usertype
*Project*
----------
project_id(PK)
project_name
employee_id(FK) ref employee_id in emplyee table
manager_id(FK) ref employee_id in emplyee table
让我更具体一点。项目必须有1名经理和几名员工。我怎么写查询? usertype列指定此员工MANAGER OR USER(普通员工)。
查询运行示例:
______ ______________ ____________
|name| |manager_name| |project_name|
John Susan CalendarIphone
Mike Susan CalendarIphone
Joe Patrick AndoridApp
Megan Susan CalendarIphone
Melek Patrick AndoridApp
如您所见,迈克可以在多个项目中工作,并且可以拥有多个经理。但管理者必须只拥有一个项目。那么我应该如何做到这一点呢?提前谢谢。
EDIT ---------------------------------------------- ---------------------------------
我有一个项目有下拉列表。我在这里选了一个项目,它根据这个项目向我展示了一个表,并列出了该项目的经理,该项目中的员工。我问项目名称只是创建了一个你可以忽略它的列。我只想看到它的经理和员工。
EDIT 2 --------------------------------------------- --------------
项目ID = 2,例如,在这个项目中,我们有1名经理和员工。
|name| |manager_name|
John Susan
Mike Susan
Joe Susan
Megan Susan
Melek Susan
答案 0 :(得分:4)
你的架构不好。它应该是这样的:
Employee*
----------
employee_id (PK)
name
manager_id (FK) ref employee_id in employee table
*Project*
----------
project_id(PK)
project_name
manager_id(FK) ref employee_id in employee table
*Project_Employee*
----------
project_id(FK) ref project_id in project table
employee_id(FK) ref employee_id in employee table
然后你可以这样做:
select
e.name as name,
em.name as manager_name
p.project_name
pm.name as project_manager_name
from Employee as e
left outer join Employee as em on em.employee_id = e.manager_id
left outer join Project_Employee as pe on pe.employee_id = e.employee_id
left outer join Project as p on p.project_id = pe.project_id
left outer join Employee as pm on pm.employee_id = p.manager_id
但是对于每个员工,可能有多个项目,员工可以在此查询中复制
<强>更新强>
select
e.name, u.is_manager
from (
select employee_id, 0 as is_manager from Project_Employee as pe where pe.idproject_id= <project id>
union all
select manager_id, 1 as is_manager from Project as p where p.project_id= <project id>
) as u
inner join Employee as e on e.employee_id = u.employee_id
order by u.is_manager desc
更新2
select
e.name as employee_name,
pm.name as manager_name
from Project_Employee as pe
left outer join Employee as e on e.employee_id = pe.employee_id
left outer join Project as p on p.project_id = pe.project_id
left outer join Employee as pm on pm.employee_id = p.manager_id
where pe.project_id = <project id>
答案 1 :(得分:0)
SELECT e.name AS name,
m.name AS manager_name,
project_name
FROM Project p
JOIN Employee e ON e.employee_id = p.employee_id
JOIN Employee m ON m.employee_id = p.manager_id
由于每个项目行都有员工和经理,因此只需访问两个不同密钥上的Employee
表即可获得员工姓名和经理姓名。然后,很自然地将查询基于Project,因为这是您正在收集的信息,因此您可以从那里获取project_name
。