Is there a way to make this SQL more efficient?

后端 未结 2 1266
别那么骄傲
别那么骄傲 2020-12-18 13:30

Consider the following tables:

department

deptid      (type:INT)
deptname    (type: TEXT)
hours       (type:INT)
active      (type:BIT)


        
相关标签:
2条回答
  • 2020-12-18 13:58

    This is shorter and probably performs faster too

    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;
    

    Start with the grouping. You don't need COUNT from the inner query. Then, join to both tables just to get the names.

    INNER JOIN is used because once the count is complete, we already know that

    1. the employees exist
    2. the department exists
    0 讨论(0)
  • 2020-12-18 14:07

    Try this query, it will work properly.

    select empname,deptname from employee,department
    where 
    employee.deptid=department.deptid and employee.deptid
    in
    (
      select deptId from employee group by deptid having count(*)>=4
    ) 
    order by empname
    
    0 讨论(0)
提交回复
热议问题