Can a compound key be set as a primary key to another table?
For instance i have the tables:
Books-with Primary Key:Product_IDClient-with Primary key:Client_IDClients_Books-with Compound Primary Key:Product_IdandClient_ID
I want to set this compound Primary key from Clients_Books as a Primary Key to another table named: Order_Details. But I don’t want to use the Product_ID and the Client_ID from the Books, Clients tables.
Does this make sense? All opinions more than welcome.
the short answer is, No – can’t do that. All of the columns in the PK (or other alternate key) must appear in the FK definition. Also remember that a table can have multiple keys – referred to as Candidate Keys (sometimes alternate keys). The primary key is simply the “best” key for your design/use (normally the narrowest one – smallest in byte size). We prefix the name of these other unique indices as “AK_{name}” – AK = Alternate Key.
What we do under this circumstance is one of two things:
Generally it isn’t a good idea to have multiple tables with the same PK definition (that is, PKs that are also FKs to another table). I say “generally” – it is important to understand the definition of your Entities.
So why use #1? The question I ask myself is whether the compound key is really the data the defines the row? Is that compound key really THE definition of a row or is it more of an FK to some other data? If it is more of an FK then I create the synthesized PK(Identity). Is an Order really the books that a client owns? An order may cause a client to own a new book – but they may not be the same thing.
Having the synthesized PK offers a few more choices down the road in future years. If the relationship needs to change in your Client_Books table then you might insulate changes to other tables.
For instance – what if a customer can own more than one copy of a book – how will you implement that? With the synthesized key you could simply remove the Unique index on the compound-key and leave it as a simple FK, then the Order_Details table would simply represent when a customer purchased their second copy. If however you had taken the compound key on Orders route, then you’d have to figure out how to redefine Order_Detail as well as Client_Books (and any other FKs that pointed to Order_Detail).
I would also ask you to evaluate whether an Order_Detail is really a Client_Book? Normally an Order causes the client to come into possession of a new book. I think of Orders as being independent of the inventory – therefore the PK on Order_Detail should not be the PK on Client_Books, Order_Detail should probably have it’s own independent PK.