SQL查询根据其他表中的外观限制结果

时间:2013-02-18 00:15:58

标签: sql

我是SQL新手,但需要为必须与数据库交互的Java程序编写一些SQL语句。我们的Java教科书仅涵盖了非常基本的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

有人可以帮忙吗?谢谢!

1 个答案:

答案 0 :(得分: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子句,它负责设计要连接的元素。