I have two mysql tables with students and school subjects that look like this:
Subjects
id | name
=================
1 | History
2 | English
3 | Science
4 | Geography
Students
id | name
=================
1 | Sergey
2 | Dmitriy
3 | Vladislav
The third table establishes a many-to-many relationship between Students and Subjects tables and also has marks column:
Marks
id | student_id | subject_id | mark
==========================================
1 | 1 | 2 | 3
2 | 2 | 2 | 5
3 | 3 | 3 | 4
4 | 1 | 4 | 5
5 | 3 | 4 | 3
6 | 2 | 3 | 4
7 | 3 | 2 | 3
8 | 1 | 1 | 4
The goal is to build a multi-dimensional array that would end up looking like below. It has to return "null" value in "mark" key if there is no such student and subject match. So it should have 12 elements for 3 students and 4 subjects (3 multiply 4).
I tried this sql query but is doesn't return records with "null" value, but records only from "Marks" table:
SELECT marks.id AS id,
students.name AS student,
marks.mark AS mark,
subjects.name AS subject
FROM students
LEFT OUTER JOIN marks ON students.id = marks.student
LEFT OUTER JOIN subjects ON marks.subject = subject.id
Desired array:
Array
(
[
"id" => 1,
"student" => "Sergey",
"subject" => "History",
"mark" => 4,
],
[
"id" => 2,
"student" => "Sergey",
"subject" => "English",
"mark" => 3,
],
...
[
"id" => 9,
"student" => "Vladislav",
"subject" => "History",
"mark" => null,
],
...
[
"id" => 12,
"student" => "Vladislav",
"subject" => "Geography",
"mark" => 3,
],
)
Does anyone know how to do this? Thank you and hope you can help me.