[英]Joining Four different tables
I've got a problem on displaying data from 4 tables, I want to display students names,his/her department,a course in that department, and the marks the student got in that course. 我在显示4个表格中的数据时遇到问题,我想显示学生的姓名,他/她的部门,该部门的一门课程以及该课程中该学生获得的分数。 My tables are student, department, courses and marks.
我的表是学生,系,课程和分数。
Student : 学生 :
student_ID
student_Fname
student_Lname
Department : 部门 :
dep_ID
dep_Name
Courses : 课程 :
course_ID
course_Name
dep_ID
Marks : 标记 :
marks_ID
student_ID
dep_ID
course_ID
score
I tried to display the data by linking student and department table to get student names and their department,the i joined department and courses to retrieve the courses included in that department but when i tried to join the student and marks table it failed. 我试图通过链接学生和部门表以获取学生姓名及其所属部门来显示数据,我加入了部门和课程以检索该部门中包含的课程,但是当我尝试加入学生并标记表时,它失败了。
This is what the query returned,it returned one student and all the courses in the sports table,which i didn't even assign marks to. 这就是查询返回的内容,它返回了一名学生和运动表中的所有课程,我什至没有给他们分配分数。 and it didn't display the second student's marks
它没有显示第二名学生的成绩
student_Fname | dep_Name | course_Name | score
--------------+-----------+----------------+------
Berhan | sports | football | 25
Berhan | sports | baseball | 25
Berhan | sports | basketball | 25
Berhan | sports | tennis | 25
This is the data i inserted in marks table. 这是我插入标记表中的数据。
marks_ID | student_ID | dep_ID | course_ID | score
---------+------------+--------+-----------+------
1 | 1 | 3 | 7 | 25
2 | 2 | 3 | 8 | 37
I tried this query: 我试过这个查询:
SELECT
s.student_Fname,
d.dep_Name,
c.course_ID,
m.score
FROM
student s
JOIN
department d ON s.dep_ID = d.dep_ID
JOIN
courses c ON c.dep_ID = d.dep_ID
JOIN
marks m ON m.student_ID = s.student_ID
As I only have 2 students in marks table, I need a result like this. 因为我的成绩表中只有2个学生,所以我需要这样的结果。
Berhan | sports | football | 25
Hiro | sports | baseball | 37
Please I need some help.. 请我需要一些帮助。
If you only want to print marks in courses in the student's department, you need to add that additional criteria to one of the joins. 如果只想在学生所在系的课程中打印成绩,则需要将该附加条件添加到其中一个联接中。
SELECT s.student_Fname
, d.dep_Name
, c.course_ID
, m.score
FROM student s
JOIN marks m ON
ON m.student_ID = s.student_ID
JOIN courses c
ON c.course_ID = m.course_ID
JOIN department d
ON c.dep_ID = d.dep_ID AND d.dep_ID = s.dep_ID
There's also no need to have dep_ID
in the marks
table. marks
表中也不需要dep_ID
。 Since course
has a foreign key to department
, putting it in marks
is redundant: the mark can't be in a different department than the one associated with the course. 由于
course
具有department
的外键,因此将其置于marks
是多余的:标记不能位于与课程关联的部门不同的部门中。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.