Foreign keys in a composite primary key
Is it possible to use one of the attributes of a composite primary key as a foreign key?
Yes, this is quite common and perfectly valid.
The best example comes from the classic many-to-many relationship. Here is a simple diagram illustrating the relationship or association or linking table (it has other names, too, but these are the most common) between Categories and Articles. Note that there are two one-to-many relationships for the Article_Categories table. This means that the foreign keys for these relationships are in the Article_Categories table.
+--------------+ +--------------+ | Categories | | Articles | +--------------+ +--------------+ | | 1 | | 1 +--------+ +--------+ | | M | | M V V +----------------------+ | Article_Categories | +----------------------+
These tables might be defined as follows:
create table Categories ( catid integer not null primary key , category varchar(37) not null ); create table Articles ( artid integer not null primary key , title varchar(255) not null , body text not null , artdate datetime not null ); create table Article_Categories ( artid integer not null , catid integer not null , primary key ( artid, catid ) , foreign key ( artid ) references Articles ( artid ) , foreign key ( catid ) references Categories ( catid ) );
The primary key of Article_Categories is a composite key. Each of its components is a foreign key to its respective table.
By the way, notice that there is no autonumber in the Article_Categories table. Using an autonumber PK in a relationship or association table is one of the more common errors made by novices.