Click here to Skip to main content
15,886,643 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
use LifeSpireDB;


create table Customer(
Customer_ID int,
Customer_Name varchar(50),
Customer_Address varchar(50),
Customer_Phone varchar(50),
primary key (customer_ID));

create table Orders(
Order_Num int,
Order_Date varchar(10),
Order_Status varchar(50),
Customer_ID int,
primary key(Order_Num),
constraint fk_PerCostumer foreign key(Customer_ID) references Customer(Customer_ID));

create table ItemsInOrder(
Order_Num int,
Item_ID varchar(15)
primary key (Order_Num, Item_ID),
constraint fk_perItemsOder foreign key(Order_Num) references Orders(Order_Num));

create table Item(
Item_UID int,
Item_ID varchar(15),
Item_Description varchar(300)
primary key (Item_UID),
constraint fk_PerItem foreign key (Item_ID) references ItemsInOrder(Item_ID));



My table Item has a foreign key which is a primary key in table ItemsInOrder, the problem is the ItemsInOrder has two primary keys.

Can anyone help me please???
Posted
Comments
Sergey Alexandrovich Kryukov 26-Feb-14 19:32pm    
If you managed to create two primary keys, your skills are so formidable that you will easily add one foreign key without any help. :-)
—SA
Alexander24 1-Mar-14 13:40pm    
Yeah I solved the problem by following some tutorials online. Thank you though
Sergey Alexandrovich Kryukov 1-Mar-14 13:42pm    
Congratulations! This is the best you could do. Thank you for reporting back.
—SA

1 solution

Hi,

First of all, you can have only one primary key. You can have multiple columns in your primary key. Such key is called a compound or composite primary key.

According to your example:
SQL
create table Item(
Item_UID int,
Item_ID varchar(15),
Item_Description varchar(300)
primary key (Item_UID),
constraint fk_PerItem foreign key (Item_ID) references ItemsInOrder(Order_Num, Item_ID));
This is important: You need to have a Order_Num column in your Item table (I haven't added it into this example). Otherwise, you just can't create a foreign key relationship!

---------------------------------------------------------------------------------------
My thoughts about your data model:
1. Why do you need a composite primary key in ItemsInOrder table? I would say that you could add ItemsInOrder_ID column and make it as simple primary key.
2. Relationship between Item and ItemsInOrder tables should be one-to-many.
3. Relationship between Orders and ItemsInOrder tables should be one-to-many.
 
Share this answer
 
v3
Comments
Jörgen Andersson 26-Feb-14 17:48pm    
Spot on.
Andrius Leonavicius 26-Feb-14 18:27pm    
Thank you, Jörgen.
Sergey Alexandrovich Kryukov 26-Feb-14 19:33pm    
5ed. :-)
—SA
Andrius Leonavicius 26-Feb-14 19:37pm    
Thank you, Sergey.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900