views:

124

answers:

4

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.

+1  A: 

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
Keltex
systemuser_id is unnecessary just have a index combining both user_id and system_id if really, really necessary. (but it probably isn't)
Pat
@Pat: True... but in the ORMs I use, each table usually has a primary key. So I just put it in there through habit.
Keltex
+3  A: 

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.

JoshJordan
+2  A: 
System            System_User        User        
------            -----------        ----
 *system_id  --->  *system_id             
  data             *user_id    <---   *user_id
                                       data

*    denotes the primary key columns
---> denotes a PK/FK relationship
Tomalak
Thank you for ALL your comments. I try remodelling with the system_user table as illustrated by Tomlak. See how that goes. Thanks again
+3  A: 

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!

eqbridges
Thanks for the SQL examples on this. I know they will come in handy down the road.