I have an SQL table that links students to classes. This table primarily has the ids user_id and class_id. Let’s suppose that each user_id is unique to the table but class_ids are not.
I want to retrieve all the instances of user_id and group them by class_id. I also wanted to be able to reprensent the result returned by SQL as the following in PHP:
array(
class_id => array(
user_id => <user info..>,
user_id => <user info..>,
user_id => <user info..>
),
class_id => array(
user_id => <user info..>,
user_id => <user info..>,
user_id => <user info..>
),
class_id => array(
user_id => <user info..>,
user_id => <user info..>,
user_id => <user info..>
)
)
I know I could call an SQL inject per class and return the users from that class and format the result into the format I need in PHP, but would there be a way to do this in one SQL request as oposed to having to do one request per class (+ 1 request to get the list of class ids)?
It is because I need to access specific classes, so I think that the key/value solution of arrays in PHP are the best way to access classes.
The short answer is no. If you use a LEFT JOIN, you could get one result set with both class info and student info however. it would not be in the exact format above, but would be a pretty simple conversion.
the result set would look like
there would be one record for each class * number of students taking that class
to elaborate
then