2014-01-18 72 views
0

如何使用select如果我有3個表?SQL select,3表

表:

school_subject(ID_of_subject, workplace, name) 
student(ID_of_student, firstName, surname, adress) 
writing(ID_of_action, ID_of_sbuject, ID_of_student) 

我想寫學生的名字和姓氏(按字母順序)誰擁有workplace=home

這可能嗎?以及如何按字母順序?

SELECT s.firstName, s.surname 
FROM student S, school_subject P, writing Z 
WHERE P.workplace = 'home' 
     AND P.ID_of_subject = Z.ID_of_subject 
     AND Z.ID_of_student = s.ID_of_student; 

回答

1
SELECT s.firstName, s.surname 
FROM student S INNER JOIN writing Z 
ON Z.ID_of_student = s.ID_of_student 
INNER JOIN school_subject P 
ON P.ID_of_subject = Z.ID_of_subject 
WHERE P.workplace = 'home' 
ORDER BY S.firstName, S.surname // Sort the list 
0

要按照字母順序排序的結果,可以使用ORDER BY關鍵字。因此,您的查詢就會變成:

SELECT DISTINCT S.firstName, S.surname 
FROM student S, school_subject P, writing Z 
WHERE P.workplace = 'home' AND 
P.ID_of_subject = Z.ID_of_subject AND 
Z.ID_of_student = S.ID_of_student 
ORDER BY S.surname, S.firstName 

DISTINCT關鍵字是必要的,因爲在寫字檯上有給定鍵ID_of_subject和ID_of_student最終更多的元組。
所以這是必要的,以避免重複名字和姓氏多次。

0

注意,每個學生由ID_of_student確定,而不是由firstNamesurname,從而@danjok說使用DISTINCT如果你只希望名字和姓氏。

如果要選擇滿足上SELECT條款您的要求(即使兩個或更多的學生有相同的firstNamesurname),你應該包括ID_of_student所有學生:

SELECT S.ID_of_student, S.firstName, S.surname 
FROM student S 
INNER JOIN writing W ON W.ID_of_student = S.ID_of_student 
INNER JOIN school_subject P ON P.ID_of_subject = W.ID_of_subject 
WHERE P.workplace = 'home' 
ORDER BY S.firstName asc, S.surname asc