views:

282

answers:

1

I am trying to add a foreign key constraint to a table in my PostgreSQL 8.4 database, but it is failing as the target field, though part of a multi-column primary key, is not in itself unique.

The database has the following structure:

Table 1 (names of primary IDs):

PrimaryType, Name
[Primary key = "PrimaryType"]

Table 2 (names of child IDs for each type of primary ID):

PrimaryType, SubType, Name
[Primary key = "PrimaryType, SubType"]
[Foreign key = "Table2.PrimaryType = Table1.PrimaryType"]

Table 3 (logs which include a primary and child ID):

PrimaryType, SubType, DATA1, DATA2, ..., DATAN
[Foreign key = "Table3.PrimaryType = Table1.PrimaryType" AND "Table3.SubType = Table2.SubType"]

Obviously, the second part of the foreign key for table 3 is what is causing the problem. I just need to ensure that the primary and subtype ID pair in the log is a valid combination.

Thanks in advance.

+2  A: 

For table 3's foreign key, change:

foreign key PrimaryType references Table1(PrimaryType)
foreign key SubType references Table2(Subtype)

to

foreign key (PrimaryType, SubType) references Table2(PrimaryType, SubTYpe)
Wayne Conrad
thanks, that worked
James