Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

database - Is there a way to make this SQL more efficient?

Consider the following 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)

Write a query to return the columns empname and deptname of the employees belonging to those departments that have a head count of 4 or more. The records should be returned in alphabetical order of empname

This was my take:

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;

How would you improve on this?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...