请考虑以下表格:
deptid (type:INT) deptname (type: TEXT) hours (type:INT) active (type:BIT)
empid (type:INT) empname (type: TEXT) deptid (type: INT) designation (type: TEXT) salary (type: INT)
编写查询以返回人员总数为4或更多的那些部门的雇员的empname和deptname列。记录应按姓氏的字母顺序返回
这是我的看法:
SELECT e1.empname, d.deptname from employee AS e1 FULL JOIN department AS d on e1.deptid = d.deptid WHERE e1.deptid IN( SELECT deptid FROM( SELECT e2.deptid, COUNT(e2.empid) FROM employee AS e2 GROUP BY e2.deptid HAVING COUNT(e2.empid) >= 4 ) ) ORDER BY empname;
您将如何对此进行改进?
这比较短,而且执行速度可能也更快
SELECT e1.empname, d.deptname from ( SELECT e2.deptid FROM employee AS e2 GROUP BY e2.deptid HAVING COUNT(e2.empid) >= 4 ) G inner join employee AS e1 on e1.deptid = G.deptid INNER JOIN department AS d on d.deptid = G.deptid ORDER BY e1.empname;
从分组开始。您不需要内部查询中的COUNT。然后,联接两个表只是为了获得名称。
*之所以使用 *INNER JOIN, 是因为一旦计数完成,我们已经知道