[DB/MySQL] Help mapping a relationship

Soldato
Joined
18 Oct 2002
Posts
5,464
Location
London Town
Brain's not working at full capacity today. I'm trying to figure out the best way to create a relationship between a set of objects and the owners of each object. Note this is the principle of what I'm doing, 'objects' are an abstract term here ;).

I have a table where each row contains a unique object, and a table of unique 'owners' of objects. One or many of the owners may own an object:
Code:
OBJECTS
id	int(11)	PK
object	varchar(255)
Code:
OWNERS
id	int(11)	PK
owner	varchar(255)
It's been a couple of years since I did any DB theory, but this is a many-to-many relationship, right?

I wish to be able to query for an object and see who owns it and vice-versa.
I have a mapping table:
Code:
ID	object_id	owner_id
1	 1		 1
2	 1		 2
3	 1		 3
4	 2		 1
5	 2		 3
6	 3		 3
Is this the best way to do it? Can anyone see any pitfalls with this?
Would it be better to remove the ID column, and instead create a PK of object_id and owner_id?
 
I don't think you need an ID field in the mapping table since it doesn't 'mean' anything - ie you won't be using that ID to select anything, because the owner_id and object_id combination will be unique (you can't own something twice.)

Setup a compound primary key on owner_id & object_id - if you keep the ID column you'd only have to create an index on one/more of the other two anyway :) (for performance)
 
Pretty sure that's the only way to do it - it's certainly the only method I've ever used and seen used.

I agree with Beansprout re: the indexing but I should hardly thing it's a major thing.
 
Thanks for the replies; always helpful to get the second opinion :).
Will be using the compound key - makes sense. Adding an auto_increment ID field for the primary key starts becoming a habit with MySQL - you just add it without really thinking whether there's a better option.
 
Back
Top Bottom