该架构如下:

Student(Snum, Sname)
Course(Cnum, Cname)
Professor(Pnum,Pname, Dept, Office)
Class(Cnum, Term, Section, Instructor)


我如何才能加入下面的两个选择中,以同时教授CS160和CS340的教师?

SELECT DISTINCT Instructor FROM class
WHERE Term = "99F" AND Cnum = "CS160"
SELECT DISTINCT Instructor FROM class
WHERE Term = "99F" AND Cnum = "CS340"


谢谢!

最佳答案

由于MySql没有intersect,因此您必须进行自我联接;就像是:

SELECT DISTINCT a.Instructor FROM class a inner join class b
using (Instructor,Term)
where a.Term "99F" and a.Cnum = "CS160" and b.Cnum = "CS340"




编辑:使用相交,您只需将intersect说明符放在示例中的两个查询之间(并且可以省略“ distinct”;“ intersect”仅返回不同的值):

SELECT Instructor FROM class
WHERE Term = "99F" AND Cnum = "CS160"
INTERSECT
SELECT Instructor FROM class
WHERE Term = "99F" AND Cnum = "CS340"


intersect是SQL标准的一部分,但MySql并未实现。确实具有intersect的SQL实现包括Oracle和Postgres。

另见mySQL versus Standard SQL

10-08 06:30