2016-02-22 50 views
0

該數據庫在這裏:http://sqlfiddle.com/#!9/bf0171兩個表上的SQL查詢;

我想找到「Prof.David」類的所有學生。然而,查詢的結果是:

Select Student.name from Student, Teacher where Teacher.s_id =Student.id and Teacher.name="Prof. David"; 
+------+ 
| name | 
+------+ 
| Tom | 
| John | 
| Mary | 
| Tom | 
| John | 
| Mary | 
+------+ 

我想結果應該是「湯姆」,只有「約翰」。有什麼問題?

回答

2

沒有Student之間的連接標準Teacher你會得到一個Cartesian product(全部來自Student記錄與所有記錄Teacher相結合)。

你大概的意思是:

SELECT 
    Student.name 
FROM Student s 
JOIN Teacher t 
    ON t.s_id = s.id 
WHERE Teacher.name="Prof. David"; 

對於SQL的新學員,我會強烈建議使用JOINLEFT JOIN等,而不是暗中加入WHERE條款中明確使用。這將有助於減少您執行的意外笛卡爾產品的數量。

+0

這實際上與聯接作品: 「這裏Teacher.s_id = Student.id和Teacher.name =」 教授。大衛「,它會正確返回」Tom「和」John「,而不使用」JOIN「 – user697911

+0

您可以隱式加入到WHERE子句中,但我不推薦它。如果需要執行左連接,會發生什麼?你的WHERE標準有一個OR語句嗎?有很多東西可能會出錯,明確使用JOIN將有助於減少事故。 –

+0

@ user697911 - 爲了討論的緣故,這裏是一個來自不同StackExchange的線程:http://程序員.stackexchange.com/q/78225 –

1

問題是您有兩個表,並且您正在使用您的查詢對這些表執行笛卡爾連接。因此,您的結果中會顯示3x2 = 6行,其中每位教師都會顯示所有3名學生的姓名。您必須根據架構中的外鍵關係以邏輯方式加入您的表。

例如:

Select A.field1, B.field2 from A join B on A.id = B.a_id

1

要看看是什麼問題,試試這個:

Select Student.name, Teacher.name from Student, Teacher 

你會得到,每一個學生與每一位教師相結合,一個人是否有什麼與其他與否的結果。需要補充的是檢查,如果老師和學生相關的條件:

Select Student.name, Teacher.name from Student, Teacher where Teacher.s_id = Student.id 

一旦你有,你可以添加更多的條件,比如只列出一個給定的老師的學生。

Select Student.name from Student, Teacher where Teacher.s_id = Student.id and Teacher.name=... 
0

您需要在其中添加連接子句。我想你正試圖選擇在某個班上有特定教師的學生。因此,舉例來說,如果你有:

table Student with columns: student_id, name 
table Teacher with columns: teacher_id, name 
table Class with columns: class_id, class_name, teacher_id 
table Class_Assignment with columns class_id, student_id 

然後將查詢將是:

Select Student.name from Student, teacher, class_assignment 
    where Student.student_id = class_assignment.student_id 
    and Teacher.teacher_id = class_assignment.teacher_id 
    and Teacher.name="Prof. David";