Question

My database model has 2 particular tables in it that require a many-to-many relationship. The tables are Systems and Users. One user can be a member of more than one system and one system has more than one user in it.

system_id is the PK in the system table and user_id is the PK in the user table. I have them linked with system_id as a FK in the user table. I can't seem to figure out a table in between the two. I had the notion of forming a system_user table and using both foreign keys in there but cant see how that would work.

Was it helpful?

Solution

You're headed in the right direction.

Create a table "system_user":

CREATE TABLE system_user (system_id INT NOT NULL, user_id INT NOT NULL);

This is not properly an entity in a strict relational modelling sense, so it doesn't require a primary key. However, you can add one if your scenarios require it.

To get all of the users in a system you'd query like so:

SELECT u.* FROM user u, system_user su WHERE su.system_id = ?

To get all of the systems a user can reach, you'd query like so:

SELECT s.* FROM system s, system_user su WHERE u.user_id = ?

Hope this helps!

OTHER TIPS

You got it right. Use a mapping table for many to many relationships. You will not need any foreign key columns in your Systems or Users tables. Your mapping table will have something like a MappingID PK, SystemID, and UserID. You could also make an entire row the PK, but its unnecessary (if you didn't want to use the MappingID). Then, simply insert pairs into this table that associate a System with a User. You can select by SystemID or UserID to get all the relationships a certain entity has. You may also include any metadata the mapping might have, like the date the association was established.

System            System_User        User        
------            -----------        ----
 *system_id  --->  *system_id             
  data             *user_id    <---   *user_id
                                       data

*    denotes the primary key columns
---> denotes a PK/FK relationship

You're on the right track. Your new system_user table would at a minimum have 3 columns:

  • systemuser_id - primary key
  • user_id - foreign key to user table
  • system_id - foreign key to system table
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top