2011-04-26 39 views
1

我一直在搞這個一段時間,似乎無法弄清楚如何將以下代碼從INTERSECT形式(不受MySQL支持)轉換爲INNER JOIN形式。MySQL INTERSECT替換內部連接 ​​- 請解釋

如果有人可以將以下代碼轉換爲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'); 

回答

1

Quassnoi的答案預先假設lot關於數據的結構。以下是更強大的(也可能是更有效):

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'; 
+0

更標準的方法,但速度更快! – 2011-04-26 20:24:59

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 

我希望你沒有真正使用SSNPRIMARY KEY

+0

這只是此刻學習的目的,但是我不能用它作爲PRIMARY KEY,如果它以某種方式加密的話? – 2011-04-26 11:27:16

+0

@丹尼斯:這不是加密,而是關於唯一性和通用性。不知道你的法律要求,但如果學生沒有'SSN',怎麼辦?如果兩個學生有同一個學生呢? – Quassnoi 2011-04-26 11:41:34

+0

好點 - 然而在美國SSN是獨一無二的,所有公民都必須擁有一個。再次感謝您的幫助。 – 2011-04-26 11:45:39

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)