37

我想使用内连接从更多表中选择数据。

这些是我的桌子。

Student (studentId, firstName, lastname)
Exam (examId, name, date)
Grade (gradeId, fk_studentId, fk_examId, grade)

我想写一份声明,说明学生参加过的考试、年级和日期。按日期排序。

这是我的声明。它运行,但我想确保我做得正确。

SELECT
  student.firstname,
  student.lastname,
  exam.name,
  exam.date,
  grade.grade
FROM grade
  INNER JOIN student
    ON student.studentId = grade.gradeId
  INNER JOIN exam
    ON exam.examId = grade.gradeId
ORDER BY exam.date
4

4 回答 4

72

几乎正确..查看连接,您指的是错误的字段

SELECT student.firstname,
       student.lastname,
       exam.name,
       exam.date,
       grade.grade
  FROM grade
 INNER JOIN student ON student.studentId = grade.fk_studentId
 INNER JOIN exam ON exam.examId = grade.fk_examId
 ORDER BY exam.date
于 2013-04-15T10:57:58.947 回答
16

正确的说法应该是:

SELECT
  student.firstname,
  student.lastname,
  exam.name,
  exam.date,
  grade.grade
FROM grade
  INNER JOIN student
    ON student.studentId = grade.fk_studentId
  INNER JOIN exam
    ON exam.examId = grade.fk_examId
ORDER BY exam.date

根据定义的外键关系引用其他表。如果您希望数据显示为已查询,则应正确引用 ID。因此,您应该将 id 引用到表中正确的外键,而不仅仅是没有定义正确关系的 id

于 2013-04-15T10:56:55.553 回答
3
SELECT
  student.firstname,
  student.lastname,
  exam.name,
  exam.date,
  grade.grade
FROM grade
 INNER JOIN student
   ON student.studentId = grade.fk_studentId
 INNER JOIN exam
   ON exam.examId = grade.fk_examId
 GROUP BY grade.gradeId
 ORDER BY exam.date
于 2013-04-15T11:02:07.320 回答
0

更专业的代码编写方式是使用“别名”——

SELECT
  s.firstname,
  s.lastname,
  e.name,
  e.date,
  g.grade
FROM grade AS g
 INNER JOIN student AS s
   ON s.studentId = g.fk_studentId
 INNER JOIN exam AS e
   ON e.examId = g.fk_examId
 ORDER BY e.date;
于 2021-08-11T16:11:54.387 回答