内部连接与 mysql 中的 3 个表
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16013364/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Inner join with 3 tables in mysql
提问by Zincktest
I want to select data from more tables with Inner join.
我想使用内连接从更多表中选择数据。
These are my tables.
这些是我的桌子。
Student (studentId, firstName, lastname)
Exam (examId, name, date)
Grade (gradeId, fk_studentId, fk_examId, grade)
I want to write a statement that shows which exam, grade and date alle the students have been to. Sorted after date.
我想写一份声明,显示学生参加过的考试、成绩和日期。按日期排序。
This is my statement. It runs, but i want to make sure that i am doing it correctly.
这是我的声明。它运行,但我想确保我做得正确。
SELECT
student.firstname,
student.lastname,
exam.name,
exam.date,
grade.grade
FROM grade
INNER JOIN student
ON student.studentId = grade.gradeId
INNER JOIN exam
ON exam.examId = grade.gradeId
ORDER BY exam.date
回答by agim
Almost correctly.. Look at the joins, you are referring the wrong fields
几乎正确.. 看看连接,你指的是错误的字段
SELECT student.firstname,
student.lastname,
exam.name,
exam.date,
grade.grade
FROM grade
INNER JOIN student ON student.studentId = grade.fk_studentId
INNER JOIN exam ON exam.examId = grade.fk_examId
ORDER BY exam.date
回答by Ajo Koshy
The correct statement should be :
正确的说法应该是:
SELECT
student.firstname,
student.lastname,
exam.name,
exam.date,
grade.grade
FROM grade
INNER JOIN student
ON student.studentId = grade.fk_studentId
INNER JOIN exam
ON exam.examId = grade.fk_examId
ORDER BY exam.date
A table is refered to other on the basis of the foreign key relationship defined. You should refer the ids properly if you wish the data to show as queried. So you should refer the id's to the proper foreign keys in the table rather than just on the id which doesn't define a proper relation
根据定义的外键关系引用其他表。如果您希望数据显示为查询,则应正确引用 ID。因此,您应该将 id 引用到表中正确的外键,而不仅仅是在没有定义正确关系的 id 上
回答by Suhel Meman
SELECT
student.firstname,
student.lastname,
exam.name,
exam.date,
grade.grade
FROM grade
INNER JOIN student
ON student.studentId = grade.fk_studentId
INNER JOIN exam
ON exam.examId = grade.fk_examId
GROUP BY grade.gradeId
ORDER BY exam.date