0

嗨,我有以下数据库架构

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

我已将以下查询写入返回谁教过 M1 或 M2 课程但不是两者的员工列表

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’))

上面的查询是否正确,因为我是 sql 新手,请帮忙

4

2 回答 2

1

这个问题通常被称为Relational Division. 下面的查询所做的是获取教授的所有教授的姓名,该教授教授诸如m1和之类的课程m2。在对教授进行过滤后,它会计算 distinct 的数量CourseName。显然,如果它只教授一门课程,它就会返回一门: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
于 2013-03-11T06:05:59.273 回答
0

尝试:

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

这假设您总共有 2 个课程,虽然不太可能,但它会为您指明正确的方向。

于 2013-03-11T06:09:57.830 回答