2015-09-08 106 views
2

我有三張表需要檢查以確定教授在哪些課程中處於活動狀態。三個表上的SQL內連接

  1. table_teacher
  2. table_course;和
  3. table_teacher_holds_course

table_teacher看起來是這樣的:

username | title 
---------+---------- 
john  | professor 
mark  | assistant 

table_course看起來是這樣的:

course_code | course_name | semester | school_year 
-------------+-------------+----------+------------ 
course_code1| course1  |semester1 | 2015 
course_code2| course2  |semester2 | 2015 
course_code3| course3  |semester3 | 2015 

table_teacher_holds_course看起來是這樣的:

username | course_code 
---------+------------- 
john |course_code1 
mark |course_code2 

當我登錄頁面時,我有教授用戶名,我想在這三張桌子上留下內部連接,以顯示教授課程從table_course

有人可以幫助我,因爲它是第一個時間給我使用sql來加入在幾個表中的搜索。

回答

1

加入在桌子上常見的領域

SELECT * 
FROM table_teacher t 
INNER JOIN table_teacher_holds_course hc ON t.username = hc.username 
INNER JOIN table_course c ON hc.course_code = c.course_code 

相關的例子:

SELECT t.title, t.username, c.course_code, c.course_name, c.semester, c.school_year 
FROM table_teacher t 
INNER JOIN table_teacher_holds_course hc ON t.username = hc.username 
INNER JOIN table_course c ON hc.course_code = c.course_code 
WHERE t.username = 'John' 

結果:

title  username course_code course_name semester school_year 
professor John  course_code1 course1  semester1 2015 
+0

錯字,缺JOIN關鍵字。 – jarlh

+0

@jarlh謝謝,修正:) – Matt

+0

感謝您的快速回答!我會嘗試這個! – useruser