简体   繁体   中英

MySQL many-to-many join even if there is no relation

I have a many-to-many relationship between students and quizzes table and would usually use 3 tables for the set-up, one for each and a junction table. I would like to list down all students with their corresponding quiz score and also list down quizzes they never took . This means that even if they have no relationship in the junction, I would like to take in the student for that quiz

The current state of the database is that I have 3 students, and 2 quizzes. The first two took the first quiz, but did not take the second. The third student took neither. This means the junction table has two entries, both pointing to quiz 1 and both the first two students with their respective scores.

The result I intend to get is like this:

student_id name quiz score total
1          john 1    5     10
1          john 2          10
2          jake 1    10    10
2          jake 2          10
3          jane 1          10
3          jane 2          10

Now, I have this query which I was hopeful that would do the trick and get all the data I need to form that structure:

SELECT 
  students.student_id, 
  students.formal_id,
  students.last_name,
  students.first_name,
  quizzes.quiz_id,
  quizzes.total,
  quizzes.description,
  _student_quiz.score

FROM 
  `quizzes` 
LEFT JOIN _student_quiz //take all quizzes, regardless if the junction had anything for it
  ON quizzes.quiz_id = _student_quiz.quiz_id
RIGHT JOIN students      //take all students regardless if they are junctioned
  ON _student_quiz.student_id = students.student_id

However, it only returns the rows containing the students and the first quiz

student_id name quiz score total
1          john 1    5     10
2          jake 1    10    10
3          jane NULL NULL  10

What changes do I need to get all the students and quizzes regardless if they have any relation with it or not?

Untested, but... I believe you need a carthesian product of the two tables.

SELECT *
FROM students CROSS JOIN quizzes
LEFT JOIN _student_quiz ON _student_quiz.student.id = students.student_id
                       AND _student_quiz.quiz.id = quizzes.quiz.id

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.

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