简体   繁体   English

如何将SQL表中的2列连接到另一个SQL表中的一列?

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

I am using MYSQL. 我正在使用MYSQL。 I have two tables in my database. 我的数据库中有两个表。

Table 1: 'courseTable' has two colums: 表1:'courseTable'有两个列:

courseId
courseName

Table 2: 'prereqTable' has two colums: 表2:'prereqTable'有两个列:

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. 表2中的两列对应于表1中的courseId。我试图运行一个查询,该查询将生成一个包含courseId的courseName和prereqCourseId的courseName的表。

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 您需要两次加入课程表,并参考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

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. AS是可选的,但建议使用,因为它提高了可读性并表明您不会忘记逗号。 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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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