For example:
I have a database of students and last classes, and for each student in a class, I also return a list of all the other students in the class. Sample table would be like
StudentID ClassID
a 1
b 1
c 1
a 2
a 3
c 2
b 3
I want to select of studentID = a classes, but also know what other students will be in his class as so:
StudentID ClassID Classmates
a 1 a,b,c
a 2 a,c
a 3 a,b
I tried doing a query like this:
SELECT * FROM
(SELECT *, GROUP_CONCAT(StudentID)
FROM enrolled GROUP BY studentID, ClassID)
AS temporary WHERE temporary.StudentID=a
The problem is that GROUP BY condenses the rows, so returning a list of b‘s classes wouldnt show anything because a is prioritized in the studentID column.
I researched everywhere and couldn’t find anything — help?
Perhaps you’re looking for something like this:
The basic idea is to generate the classmates lists by grouping on just
classidand then join that toenrolledso that you can select the student you’re interested in.When you use
where e.studentid = 'a', you get this:filtering on
e.studentid = 'b'yields:and filtering on
e.studentid = 'c'gives you this: