0

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.

1 Answer 1

2

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)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.