MySQL,查找“经理”的所有员工

时间:2013-06-02 12:03:41

标签: php mysql database laravel

我有一个“经理”,可以分配到许多地方,并处理每个地点的一个部门。我想要一个可以抓住所有这些的查询:

http://sqlfiddle.com/#!2/33453c/1

在上面的示例中(在链接中),您可以看到我已经计算了每个部门中有多少员工。

Managers Employees 位于名为 staff 的表中,我不希望查询检索管理器记录。所以user_role =“员工”;

我在 laravel 中将其作为原始查询运行,因此我可以将它们作为对象检索:

$employees= DB::query('query goes in here')->get();

一个例子是拥有staff_id'5'的经理让所有位置和经理所在的部门的每个员工都有意义吗?

我的猜测是:

First Query SELECT ALL FROM staff, locations and departments where user_role = "employee"

Second Query SELECT ALL FROM staff, locations and departments where manager id=5

删除所有不满足第二个查询的结果,但同时加入两个查询?

非常感谢帮助。

1 个答案:

答案 0 :(得分:1)

我认为这就是你想要的。离开加入员工部门的经理部门,并获得每个部门中“员工”员工的数量(即使为0)

下面显示了经理#2(如果你想看到所有经理,你可以通过经理ID和部门ID消除where子句和组)

SELECT dept.name AS dept, loc.address1 AS loc, emp.*
FROM staff AS mgr
INNER JOIN department_staff AS mgr_dept
    ON mgr_dept.staff_id = mgr.staff_id
INNER JOIN departments AS dept
    ON mgr_dept.dept_id = dept.dept_id    
INNER JOIN location_staff AS mgr_loc
    ON mgr_loc.staff_id = mgr.staff_id
INNER JOIN locations AS loc
    ON mgr_loc.loc_id = loc.loc_id    
INNER JOIN (
  SELECT emp.*, dept.dept_id, loc.loc_id
  FROM staff AS emp
  INNER JOIN department_staff AS dept
    ON emp.staff_id = dept.staff_id
  INNER JOIN location_staff AS loc
    ON emp.staff_id = loc.staff_id
  WHERE emp.user_role = "Employee"
) AS emp
  ON emp.loc_id = mgr_loc.loc_id 
  AND emp.dept_id = mgr_dept.dept_id
WHERE mgr.staff_id = 2