0

我正在使用 MYSQL。我的数据库中有两个表。

表 1:'courseTable' 有两列:

courseId
courseName

表 2:“prereqTable”有两列:

courseId
prereqCourseId

表 2 中的两列都对应于表 1 中的 courseId。我正在尝试运行一个查询,该查询将生成一个表,其中包含 courseId 的 courseName 和 prereqCourseId 的 courseName。

我被困在这里:

SELECT `course`.courseName, `prereq`.prereqCourseId FROM `course`
LEFT OUTER JOIN `prereq`
ON `course`.courseId = `prereq`.courseId
4

3 回答 3

1

您需要参考 prereqTable 表两次加入课程表

SELECT a.courseName,c.courseName
FROM courseTable AS a
LEFT OUTER JOIN prereqTable AS b ON a.courseId=b.courseId
LEFT OUTER JOIN courseTable AS c ON b.prereqCourseId=c.courseId
于 2012-07-19T19:33:23.400 回答
1

如果你想加入同一个表两次,你必须使用别名。

SELECT p.name AS parent, c.name AS child
  FROM relations AS r
  LEFT JOIN nodes AS p
    ON(p.id=r.parent)
  LEFT JOIN nodes AS c
    ON(c.id=r.child )

AS是可选的,但建议使用,因为它提高了可读性并表明您不只是忘记了逗号。比较:

SELECT  a b, c d, e, f, g, h i, ...

SELECT a AS b, c AS d, e, f, g, h AS i, ...
于 2012-07-19T19:39:09.857 回答
0

可以将同一个表连接两次,您只需为每个实例中的表分配不同的别名,以便您可以从表的适当实例中选择列。像这样:

SELECT
    `course_main`.courseName,
    `course_prereq`.courseName AS `prereqCourseName`

FROM `course` AS `course_main`

LEFT OUTER JOIN `prereq`
ON `course_main`.courseId = `prereq`.courseId

LEFT OUTER JOIN `course` AS `course_prereq`
ON `course_prereq`.courseId = `prereq`.prereqCourseId
于 2012-07-19T19:30:59.473 回答