this is my database schema
student table:
studentid (PK) |studentname
1 |A
class table:
classid (PK) |classname
1 |Math
2 |Science
teach table:
teachid (PK) | classid | studentid
1 | 1 | 1
2 | 2 | 1
quiz table:
quizid (PK) |classid | quizname
1 |1 | mathquiz
2 |2 | science quiz
quizscore table:
quizscoreid(PK) | quizid |studentid |score
1 | 1 |1 |60
2 | 2 |1 |0
and this is my sql query that i use :
SELECT
quiz.quizid,
teach.classid,
student.studentname,
student.studentid,
quizscore.score,
quiz.quizname,
class.classname
FROM teach
INNER JOIN class
ON teach.classid = class.classid
INNER JOIN student
ON teach.studentid = student.studentid
INNER JOIN quiz
ON quiz.classid = '1'
LEFT JOIN quizscore
ON teach.studentid = quizscore.studentid
WHERE
teach.classid='1' AND
teach.classid = quiz.classid AND
quiz.quizid = '1'
ORDER BY studentid ASC
and its output like this:
studentid |quizid |classid | studentname |classname | quizname | score
1 | 1 |1 | A |Math | mathquiz | 60
1 | 1 |1 | A |Science | mathquiz | 0
while im expecting like this:
studentid | quizid |classid | studentname |classname | quizname | score
1 | 1 |1 | A |Math | mathquiz | 60
please help me correct my sql query
There are two joins missing I found, I have made the correction in SQL. Try it, hope you will get expected result.
SELECT
quiz.quizid,
teach.classid,
student.studentname,
student.studentid,
quizscore.score,
quiz.quizname,
class.classname
FROM teach
INNER JOIN class
ON teach.classid = class.classid
INNER JOIN student
ON teach.studentid = student.studentid
INNER JOIN quiz
ON quiz.classid = tech.classid
LEFT JOIN quizscore
ON (teach.studentid = quizscore.studentid
and quiz.quizid = quizscore.quizid)
WHERE
teach.classid='1' AND
teach.classid = quiz.classid AND
quiz.quizid = '1' and
quiz.classid = '1'
ORDER BY studentid ASC
SELECT
A.studentid,
D.quizid,
A.classid,
C.studentname,
B.classname,
D.quizname,
E.score
FROM
teach A
LEFT JOIN class B ON A.classid=B.classid
LEFT JOIN student C ON A.studentid=C.studentid
LEFT JOIN quiz D ON A.classid=D.classid
LEFT JOIN quizscore E ON D.quizid=E.quizid AND E.studentid=A.studentid
WHERE
A.studentid=1 AND
D.quizid=1 AND
A.classid=1;
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.