我有一个数据库:
Staff Name
1 Blake
2 Jake
Mgr Emp
2 6
2 8
3 5
4 7
是否可以搜索所有员工,但将其列在经理下?
全选:
Staff Name Mgr 1 Blake null 2 Jake null 6 Scott 2 8 Jack 2 3 Clark null 5 Martin 3 4 Smith null 7 Scott 4
有没有办法在搜查员工时查找团队?
搜索:" Scott"
返回:
Staff Name Mgr 2 Jake null 6 Scott 2 8 Jack 2
答案 0 :(得分:0)
假设你有:
您可以这样做:
SELECT employees.id, employees.name, managers.id, managers.name
FROM staff as employees
LEFT JOIN employee_managers ON (employee_managers.employee_id = employees.id)
LEFT JOIN staff as managers ON (managers.id = employee_managers.manager_id)
对于第二个查询,您将where子句添加到上述查询中:
WHERE managers.name = "Scott" OR employees.name = "Scott"
注意:如果您可以更改数据库的型号,我建议您 在staff_managers表的employee_id上设置UNIQUE约束, 这样一个员工只能拥有一名经理。
答案 1 :(得分:0)
http://rextester.com/OAREI7219是解决方案
CREATE TABLE Managers (
MgrID int ,
EmpID int
)
CREATE TABLE Staff (
EmpID int,
name nvarchar(50)
)
查询是;
SELECT
s.EmpID AS Staff,
s.name AS Name,
m.MgrID
FROM Staff s LEFT JOIN Managers m ON s.EmpID = m.EmpID ;
GO
答案 2 :(得分:0)
让所有员工与他们的经理联系。尝试
Select staff.Id,Staff.name,managers.mgr
From staff left join managers on staf.id=managers.emp
搜索员工并与经理一起获得他的团队。尝试
- 搜索:'scott'
Select staff.Id,Staff.name,managers.mgr
From staff left join managers on staf.id=managers.emp
Where managers.mgr =(select t.mgr from managers as t where t.emp='scott')
Union all
Select staff.Id,Staff.name,managers.mgr
From managers left join staff on staf.id=managers.mgr
Where managers.emp='scott'