the following is my database schema with data inserted into it:
CREATE TABLE students (`id` int, `name` varchar(9));
CREATE TABLE subjects (`id` int, `credit` int, `name` varchar(43));
CREATE TABLE student_subjects (`studentId` int, `subjectId` int);
INSERT INTO students (`id`, `name`) VALUES
(1, 'student 1'),
(2, 'student 2'),
(3, 'student 3');
INSERT INTO subjects (`id`, `credit`, `name`) VALUES
(1, 3, 'subject 1'),
(2, 4, 'subject 2'),
(3, 4, 'subject 3');
INSERT INTO student_subjects (`studentId`, `subjectId`) VALUES
(1, 2),
(2, 2),
(2, 3),
(3, 1),
(3, 3);
I want to get all students and all of them subjects if they have a specific subject and I want to include for each student all its subjects.
For example, I want to get all students which have subject 2
the result should be like this:
| studentName | subjectName |
|---|---|
| student 1 | subject 2 |
| student 2 | subject 2 |
| student 2 | subject 3 |
I can use where to filter students which have subject 2 like this
select students.name as studentName, subjects.name as subjectName from students
left join student_subjects on students.id = student_subjects.studentId
left join subjects on subjects.id = student_subjects.subjectId
where subjects.id = 2
but it will filter data for other subjects
Any idea to do that? Thanks