如何从mysql中没有子查询的两个表中获取计数

时间:2012-01-26 05:28:29

标签: php mysql

我有两张桌子,

department  
———-  
deptid (type: INT)  
deptname (type: TEXT)  
hours (type: INT)  
active (type: BIT)  

employee  
——–  
empid (type: INT)  
empname (type: TEXT)  
deptid (type: INT)  
designation (type: TEXT)  
salary (type: INT)  

现在如何在不使用子查询的情况下进行查询,该子查询返回属于头数为4或更多的部门的员工的列empname和deptname。记录应按empname的字母顺序返回。

3 个答案:

答案 0 :(得分:1)

因为您有汇总条件(人数为4或更多),这意味着如果没有子查询,您将无法获得empname,只能获得deptname

答案 1 :(得分:0)

Select E.empName, D.DeptName, count(E2.EmpID)
FROM Department D
LEFT JOIN Employee E
  ON E.DeptID = D.DeptID
LEFT JOIN Employee E2
  ON E.DeptID = D.DeptID
GROUP BY E.EmpName, D.DeptName
Having count(e2.empID) >=4

答案 2 :(得分:0)

我没有测试过,但这对我来说是正确的

SELECT empname, deptname, department.deptid
FROM employee JOIN department ON employee.deptid = department.deptid
GROUP BY department.deptid
HAVING count(department.deptid) >= 4
ORDER BY empname;
相关问题