简体   繁体   中英

How to join 2 columns in a SQL table to one column in another SQL table?

I am using MYSQL. I have two tables in my database.

Table 1: 'courseTable' has two colums:

courseId
courseName

Table 2: 'prereqTable' has two colums:

courseId
prereqCourseId

Both columns in table 2 correspond to courseId in table 1. I am trying to run a query that will result in a table that contains the courseName for the courseId and the courseName of the prereqCourseId.

I am stuck here:

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

You need to join the course table twice with referecing to prereqTable table

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

If you want to join the same table twice, you have to use aliases.

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 )

The AS are optional but recommended, as it improves readability and indicates you didn't just forget a comma. Compare:

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

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

Joining the same table twice is possible, you just have to assign a different alias to the table in each instance so that you can select columns out of the appropriate instance of the table. Like so:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM