2013-02-18 73 views
0

我是一名SQL新手,但需要爲必須與數據庫交互的Java程序編寫一些SQL語句。我們的Java教科書僅涵蓋非常基本的SQL命令,而且我無法獲得更高級的(按我的標準)工作。基於其他表中的外觀限制結果的SQL查詢

這裏的情況:

該數據庫有5個表。

Teacher: TeacherID (PK), LastName 
Class: ClassID (PK), Description 
Room: Building, Room Number, PK is the combo of those two 
TeachingAssignments: TeacherID(FK), ClassID(FK) 
ClassRoomAssignments: ClassID(FK), Building, Room Number(combo is FK) 

我需要給剛剛的只有那些教師,班級,和場地完全分配的LastName, ClassID, and Building。也就是說,如果一個班級既有老師也有房間分配,那麼我需要給這個班級的ID,指定的老師的姓以及指定的建築物。

我不知道如何繼續。

我一直在玩弄類似以下,但他們不是爲我工作的語句:

SELECT Teacher.LastName, Class.ClassID, Room.Building 
FROM Teacher, Class, Room, TeachingAssignments, ClassRoomAssignments 
WHERE Teacher.TeacherID = TeachingAssignments.TeacherID 
    AND Room.Building = ClassRoomAssignments.Building 
    AND Class.ClassID = TeachingAssignments.ClassID 
    AND Class.ClassID = ClassRoomAssignments.ClassID 

誰能幫助?謝謝!

+0

作爲警告 - 您基本上正在創建一個連接樹。加入不同的表格(可能)不同的行數。這可能會導致意想不到的結果。 – 2013-02-18 00:20:06

回答

1

你的問題是你需要爲你的表添加相應的連接。

而不是做:

SELECT Teacher.LastName, Class.ClassID, Room.Building 
FROM Teacher, Class, Room, TeachingAssignments, ClassRoomAssignments 
WHERE Teacher.TeacherID = TeachingAssignments.TeacherID 
AND Room.Building = ClassRoomAssignments.Building 
AND Class.ClassID = TeachingAssignments.ClassID 
AND Class.ClassID = ClassRoomAssignments.ClassID 

你需要類似的東西

SELECT Teacher.LastName, Class.ClassID, Room.Building 
FROM 
Teacher INNER JOIN TeachingAssignments 
    ON Teacher.TeacherID = TeachingAssignments.TeacherID 
INNER JOIN Class 
    ON Class.ClassID = TeachingAssignments.ClassID 
INNER JOIN ClassRoomAssignments 
    ON Class.ClassID = ClassRoomAssignments.ClassID 
INNER JOIN Room 
    ON Room.Building = ClassRoomAssignments.Building 

正如你可以看到每一個INNER JOIN其次是它各自的ON子句中負責設計的這件是即將加入。

+0

感謝您的反饋,但當我嘗試時收到以下錯誤消息:錯誤:列名'CLASS.CLASSID'位於FROM列表中的多個表中。 – 2013-02-18 03:17:41