MySQL INTERSECT替换INNER JOIN - 请解释

时间:2011-04-26 11:15:00

标签: mysql

我一直在搞乱这一段时间,似乎无法弄清楚如何将以下代码从INTERSECT表单(MySQL不支持)转换为INNER JOIN表单。

如果有人可以将以下代码转换为INNER JOIN,我想我可以从这个例子中理解。提前致谢!

(SELECT Student.SSN, First_Name, Last_Name 
FROM Student, Enrolls 
WHERE Enrolls.SSN = Student.SSN AND CourseNo='CSC132')

INTERSECT

(SELECT Student.SSN, First_Name, Last_Name 
FROM Student, Enrolls 
WHERE Enrolls.SSN = Student.SSN AND CourseNo='CSC134');

3 个答案:

答案 0 :(得分:2)

SELECT  SSN, First_Name, Last_Name 
FROM    student s
WHERE   (
        SELECT  COUNT(*)
        FROM    enrolls e
        WHERE   e.ssn = s.ssn
                AND e.courseNo IN ('CSC132', 'CSC134')
        ) = 2

我希望你没有真正使用SSN PRIMARY KEY

答案 1 :(得分:1)

Quassnoi的回答预先设定了一个关于数据结构的很多。以下是更强大的(并且可能更有效):

 SELECT  s.SSN, s.First_Name, s.Last_Name 
 FROM    Student s,
         Enrolls e1,
         Enrolls e2
 WHERE e1.SSN=s.SSN
 AND   e2.SSN=s.SSN
 AND   e2.SSN=e1.SSN
 AND   e1.CourseNo='CSC132'
 AND   e2.CourseNo='CSC134';

答案 2 :(得分:0)

我认为最好这样做

SELECT Student.SSN, First_Name, Last_Name FROM

(SELECT Student.SSN, First_Name, Last_Name 
FROM Student, Enrolls 
WHERE Enrolls.SSN = Student.SSN AND CourseNo='CSC132') AS a

INNER JOIN

(SELECT Student.SSN, First_Name, Last_Name 
FROM Student, Enrolls 
WHERE Enrolls.SSN = Student.SSN AND CourseNo='CSC134') AS b

USING (Student.SSN, First_Name, Last_Name)