views:

77

answers:

3

Say I have the following tables and columns:

comp: 
    id, 
    model

dvd: 
    id, 
    model

comp2dvd: 
    id, 
    id_comp, 
    id_dvd

A computer can have multiple dvd drives, even of the same model, and a dvd drive can appear in multiple computers. How do I make it so that comp2dvd table can have only existing comp and dvd ids?

Thanks

A: 

By adding foreign keys to id_comp and id_dvd?

k_b
This would work if the link table had just id_comp and id_dvd, but that doesn't work for me. If I try to add foreign keys, I get this error: The columns in table 'dvd' do not match an existing primary key or UNIQUE constraint.
Gromul
+1  A: 

Why not just go with a straight join table? You could add a constraint on the join table to only allow the use of one DVDID + computer combination.

Computer  -----> CompDVD  <------ DVD --------> Model
ID               CompID           ID            ID
                 DVDID
RobS
I noted that a computer can have two instances of the same dvd drive. The dvd table holds just unique dvd models.
Gromul
Well, you said "computer can have multiple dvd drives, even of the same model" but I assume each computer's actual physical drives are unique, surely?
RobS
I'd put the unique DVD models into a separate table, as illustrated
RobS
@Gromul this would work - The join table enforces a many to many relationship and you just put a constraint on each ID in the CompDVD so that it exists in the appropriate table +1
Romain Hippeau
+1  A: 

you cannot normally have a foreign key reference without an enforcing index which identifies a column or combination of columns as unique (such as, but not limited to, a primary key)

comp should have id as primary key

dvd should have id as primary key

comp2dvd should have id as primary key

comp2dvd should have id_comp as foreign key references(comp.id)

comp2dvd should have id_dvd as foreign key references(dvd.id)

DO NOT let comp2dvd have a unique index or constraint on the pair of columns (id_comp, id_dvd), since you need duplicates for computers with multiple identical drives

Cade Roux