1

I have a basic multi-school management system that I am working on for fun in order to learn querying from a MySQL database.

I am doing a number of joins from tables such as students, schools,student_grade, grade_school etc. I now want to get a list of all subjects the student has been assigned. Since there are multiple possible rows, I have a student_subject table to hold the student_id and then the subject_id values.

The following query gets me the student's name, and their grade:

SELECT a.id,a.firstnames,a.surname,d.gradename 
FROM students a 
LEFT JOIN student_grade b ON a.id=b.studentid
LEFT JOIN grade_school c ON c.id=b.gradeid
LEFT JOIN grades d ON c.gradeid=d.id
WHERE a.schoolid=? AND b.gradeid=? ORDER by a.surname ASC

This results in each row returned to be the student's name and their grade, like this:

ID   |   Firstname    |   Surname    |   Grade
 1   |     John       |      Doe     |     4
 5   |      Sarah     |   Marshall   |     7

How can I get all the subjects the student is assigned and put them all in a column "subject_ids" to get a result as follows:

ID   |   Firstname    |   Surname    |   Grade  |  Subjects
 1   |     John       |      Doe     |     4    |  5,54,2,56
 5   |      Sarah     |   Marshall   |     7    |  2,4,12,17

My table structures are as follows:

Table `students`
id | firstnames | surname | schoolid


Table `student_grade`
id | studentid | gradeid


Table `grade_school`
id | gradeid| schoolid


Table `grades`
id | gradename|


Table `student_subject`
id | studentid| subjectid
 4 |    1     |    5
 5 |    1     |    54
 6 |    1     |    2
 7 |    1     |    56
 8 |    5     |    2
 9 |    5     |    4
10 |    5     |    12
11 |    5     |    17
1

2 Answers 2

2

Try this:

SELECT a.id,a.firstnames,a.surname,d.gradename, GROUP_CONCAT(s.subjectid)
FROM students a 
LEFT JOIN student_grade b ON a.id=b.studentid
LEFT JOIN grade_school c ON c.id=b.gradeid
LEFT JOIN grades d ON c.gradeid=d.id
LEFT JOIN student_subject s ON s.studentid=a.id
WHERE a.schoolid=? AND b.gradeid=? ORDER by a.surname ASC

also check this or this

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks, this however only returns one student. But I think I understand the concept.
maybe add GROUP BY a.id
1

The GROUP_CONCAT() function will do what you want here.

This question is a dup of Can I concatenate multiple MySQL rows into one field?

1 Comment

Thank you, i'll have a look at GROUP_CONCAT()

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.