tags:

views:

337

answers:

1

I'm relatively new to MySQL, and I was wondering if it was possible to prevent duplicate entries in a table pivot/mapping which has no primary key and a many-to-many relationship. A simple example:

table 1
table1ID
field
field

table 2
table2ID
field
field

pivot table
table1ID
table2ID

Since a many-to-many relationship would mean that a [single] primary key cannot be used, is there a concise way (1-2 queries) to prevent a duplicate entry (same table1ID, table2ID pair) from being added?

Edit: Obviously, this can be done through a SELECT and a loop through the results, but not only is that an extra call, but there's an extra loop.

A: 

The pivot table should have a primary key of both columns:

PRIMARY KEY(table1ID, table2ID)

this speeds up lookups and ensures uniqueness. You could also add a UNIQUE key in the other direction (table2ID, table1ID)

Todd Gardner
Just to clarify, would UPDATE ON DUPLICATE KEY apply if BOTH are Primary Keys?
Not sure what you mean. The statement above means the primary key is actually the concatenation of the two items (sorta), so if one is different, then it won't collide on uniqueness
Todd Gardner
Apparently, Yes. http://lists.evolt.org/archive/Week-of-Mon-20000828/016482.html
Thanks, Todd!15char