0

我是 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

任何人都可以帮忙吗?谢谢!

4

1 回答 1

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 子句,该子句负责设计要连接的元素。

于 2013-02-18T00:52:36.547 回答