简体   繁体   中英

mySql Subquery Answers Check Final Exam Questions

I'm having some doubts regarding these answers of mine, would greatly appreciate if you guys can clarify if im right or wrong,

Questions:

An employee may be assigned to more than one project and a project may have many employees. Consider the following relational schema and write SQL statements for the below queries.

Employees (empID, empName, empDOB, empAddress, salary, deptID, jobID)

Assignments (empID, projID, assignedDate, completionDate, status)

Projects (projID, projDescription, startDate, endDate, projType)

(a) Display the names of employees who were born before 31st Jan 1980 and assigned a 'Office Complex' type project, sort results in ascending order of name. (5 marks)

(b) Retrieve the empIDs who are assigned at least two (2) projects. (5 marks)

Answers:

(a) SELECT empName FROM Employees WHERE empDOB < '31-01-1980' AND projType = (SELECT projType FROM Projects WHERE projType = 'Office Complex') ORDER BY empName; 

(b) SELECT empID FROM Employees GROUP BY (SELECT projID From Projects) HAVING COUNT(*)>1 ORDER BY empID; 

I feel the answer for the second question may be wrong.

For part a), I'd join the tables to match up employees with the project type:

 SELECT empName 
 FROM Employees 
 INNER JOIN Assignments ON Assignments.empID = Employees.empID
 INNER JOIN Projects ON Assignments.projID = Projects.projID
 WHERE empDOB < 31-01-1980 AND projType = 'Office Complex' 
 ORDER BY empName;

As it stands, your statement attempts to find projType = 'Office Complex' in the Employee table, where it doesn't exist.

For the second question, everything you need is in the Assignments table:

SELECT empID, COUNT(projID)
FROM Assignments
GROUP BY empID
HAVING COUNT(projID) > 1

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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