0

I have two tables as

tbl_student

student_id  student_name     student_address
1           Mark Anderson    Park Avenue #203 CA  

tbl_student_subjects

RecordID fkStudentID fkSubject
1           1         English
2           1         Zoology
3           1         Botany

How can I get the student details with all its subject with a single join and student details should not be repeated.

Thanks in advance Umar

0

2 Answers 2

1
select student_id, student_name, student_address, GROUP_CONCAT(fkSubject)
from tbl_student
left join tbl_student_subjects ON tbl_student.student_id = tbl_student_subjects.fkStudentID
group by tbl_student.student_id

GROUP_CONCAT docs. Note that it's length-limited, by default, to 1024 characters, so if you've got any overachiever students whose class details will exceed 1024 characters, the extra class information will get silently dropped.

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

2 Comments

Dear Sir,Many Many thanks for your help. This works for me when I need the subjects only with each student, but if I need more attributes also like subject code from subjects table, how can I get the subject code attribute also?
just add it to the query. if you need to directly relate the subject and codes, then something like GROUP_CONCAT(CONCAT(fkSubject, ' ', extra, fields, here)) should do the trick.
0

Something like this

SELECT tbl_student.student_name, tbl_student.student_address, tbl_student_subjects.fksubject 
FROM tbl_student 
INNER JOIN tbl_student_subjects ON tbl_student_subjects.fkstudentID = tbl_student.student_id
WHERE 1=1 
GROUP BY tbl_student.student_id

Comments

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.