Вопрос

Hi i have the following database schema

Professor (EMP ID,Name,Status,Salary,Age)
Course(Course ID,Course Name,PoINts)
Works(Course ID,EMP ID,Class ID)

I have written the following query to Return list of employees who have taught course M1 or M2 but NOT both

SELECT p.empid,p.name
FROM professor p,course c,works w
WHERE p.empid = w.empid
AND w.courseid = c.courseid
AND ((c.coursename = ‘m1’ AND c.coursename != ‘m2’)
OR
(c.coursename = ‘m2’ AND c.coursename != ‘m1’))

Is the above query right as i am new to sql please help

Это было полезно?

Решение

This problem is usually termed as Relational Division. What the query below does is it gets all the professor's name which teaches the courses such as m1 and m2. After the professors has been filtered it then counts the number of distinct CourseName. Obviously, it will return one if it only teaches one course :D.

SELECT  a.EmpID, a.Name
FROM    Professor a
        INNER JOIN Works b
            ON a.EmpID = b.EmpID
        INNER JOIN  Course c
            ON b.CourseID = c.CourseID
WHERE   c.CourseName IN ('m1', 'm2')
GROUP   BY a.EmpID, a.Name
HAVING  COUNT(DISTINCT c.CourseName) = 1

Другие советы

Try:

SELECT p.empid,p.name
FROM professor p join works w on
p.empid = w.empid
having count(w.courseid) = 2

This assumes you have 2 classes total, which, while unlikely, it will point you in the right direction.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top