简体   繁体   English

如何在没有子查询的情况下从两个表中获取计数

[英]how to get count from two tables without subquery in mysql

i have two tables, 我有两张桌子,

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)  

now how to make query without using subquery that returns the columns empname and deptname of the employees belonging to those departments that have a head count of 4 or more. 现在,如何在不使用子查询的情况下进行查询,该子查询返回员工总数为4或以上的部门的雇员的empname和deptname列。 The records should be returned in alphabetical order of empname. 记录应按empname的字母顺序返回。

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

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

I haven't tested it, but this looks right to me 我还没有测试过,但这对我来说似乎正确

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;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM