簡體   English   中英

如何在沒有子查詢的情況下從兩個表中獲取計數

[英]how to get count from two tables without subquery in 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的字母順序返回。

因為您具有匯總條件 (頭數為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

我還沒有測試過,但這對我來說似乎正確

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