简体   繁体   English

如何 SELECT 查询包括联结表

[英]How to SELECT query including a junction table

I have three tables:我有三张桌子:

students学生

student_ID
Firstname
Lastname

course课程

course_ID
course_Name
semester

enroll注册

student_ID
course_ID

enroll is the junction table instead of having the many to many relationships.注册是联结表,而不是多对多关系。

I need to create a SELECT statement that will return four columns: student_ID Firstname course_ID course_Name from two tables after enrollment.我需要创建一个 SELECT 语句,该语句将在注册后从两个表中返回四列: student_ID Firstname course_ID course_Name Here in the enroll table, I can only see the which student_ID is enrolled in which course_ID by there primary key.在登记表中,我只能通过那里的主键查看哪个 student_ID 在哪个 course_ID 中登记。 But if I want to see what is the course name reference with specific course_ID enrolled by the specific student_ID, how should I write the query.但是,如果我想查看特定 student_ID 注册的具有特定 course_ID 的课程名称引用,我应该如何编写查询。

Actually I want to fetch the student_ID , Firstname , course_ID , course_name in a website to see which is students are enrolled in which course_name not only the course_name .实际上,我想在网站中获取student_IDFirstnamecourse_IDcourse_name ,以查看哪些学生注册了哪些course_name ,而不仅仅是course_name That is why I think I will need to write a select query.这就是为什么我认为我需要编写一个 select 查询。

It will be helpful if anyone can help me with that.如果有人可以帮助我,那将会很有帮助。

This should work for mysql or sql server, you didn't say which you were using.这应该适用于 mysql 或 sql 服务器,您没有说您使用的是哪个服务器。 You might want to limit it or use a where clause if you have a lot or rows.如果您有很多或行,您可能想要限制它或使用 where 子句。

SELECT students.studen_ID, students.Firstname, course.course_ID, course.course_Name
FROM students
JOIN enroll ON (enroll.student_ID = students.student_ID)
JOIN course ON (course.course_ID = enroll.coruse_ID)

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

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