我正在使用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
答案 0 :(得分: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
答案 1 :(得分: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, ...
答案 2 :(得分: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