I have a table that stores user information in a table in a MySQL database. I need a way to store what classes those users are associated with.
Class as in… school.
The classes that are associated to the users needs to be dynamic and can be different for every user.
I was thinking of having a specific number of columns that are associated with classes in my user profile table. And then just insert a classId into a row if they are associated to the class. And just keep filling it up.
This seems dirty and really bad. What are my other options where I can query the database to know what classes a user is associated with?
Set up two extra tables: one for classes (id, name, …) and an association table to associate users with their classes. The association table would have two columns: the user ID and the class ID. Then to get a user’s classes:
where
Xis the user’s ID. Similarly, to get the users in a class:You’d probably want to set the PK for the association table to (user_id,class_id) and index each column individually.
If you wanted more information about the class than just the ID, do a join: