tags:

views:

43

answers:

3

i have table A and table B. I have a bridge table called tableC

in table C i have:

ID
tableA_ID
tableB_ID

ID is the primary key.

i also want to enforce the combination of tableA_ID and tableB_ID to be unique so there are no duplicate records.

how do i enforce this?

A: 

Drop the ID column then make the other two columns the primary key and their uniqueness will be enforced by the database server. It's not really necessary to have the ID column - even though it serves as a handy way of referencing a particular record - as the uniqueness of the other two columns will mean that they are sufficient to reference a particular record.

You may also want to put an index on this table, that includes bothe columns, to make access faster.

belugabob
If you make them PART of the primary key, the combinations will NOT be unique, the id can be used as a "history" or "order" but other than that it is useless
astander
@astander - you're right about making them part of the primary key, and I should have known this (Good explanation in your answer). I usually don't include a surrogate key in join tables (and suggested that the ID was dropped), but will remember this in future.
belugabob
@belugabob, correct the mistake and this answer can be UPvoted!
Tony Andrews
@Tony - My answer has been reworded, as you suggested, feel free to upvote (But I won't cry if you don't)
belugabob
+2  A: 

Make the PRIMARY KEY tableA_ID and tableB_ID, EXCLUDING ID

lets say we have a table TABLEA with values

tableAID
1
2
3

and table TABLEB with values

tableBID
4
5
6

making the primary key (ID, tableA_ID, tableB_ID) will not work eg.

ID | tableAID | tableBID
1 | 1 | 4
2 | 1 | 4

will work fine with the above pk, but you need PRIMARY KEY (tableA_ID, tableB_ID)

astander
He already has a primary key, I assume that can't be replaced.
skaffman
well if he cannot change the PK he should at least use an unique index...
astander
+3  A: 
create unique index myIdx on tableC(tableA_ID, tableB_ID)

or whatever the syntax for your particular database system is.

skaffman
This seems to be a many-to-many link table. In this case, `id` is usually redundant.
Quassnoi
Very likely, but without knowing for sure, I just answered the question.
skaffman