MySQL – Adding Multiple Foreign Keys to Single Table

foreign keyinnodbMySQLtable

I'm trying to add multiple foreign keys to the same table; however, the error code 1215: Cannot add foreign key constraint keeps popping up. I've read other people's posts on this same topic and tried to add innodb, but the error is still popping up. Any help is appreciated!

Here's my code:

Create Database if not exists Research;
Use Research;

Create table if not exists CompanyInfo
(
CID int primary key, Company varchar(45), 
SIC int, InnovativeIndex int
) 
engine = innodb;

Create table if not exists TimePeriod
(
Year int primary key, GDP int, GDPgrowth int, 
inflation decimal(5,2), unemployment decimal(5,2)
) 
engine = innodb;

Create Table If not exists CompanyRank 
(
CID int, Year int, IndexYN int, SPRank int, FortuneRank int, 
primary key (CID, Year), index (CID), Index(year),
foreign key (CID) references CompanyInfo.CID,
foreign key (Year) references TimePeriod.Year
) 
engine = innodb;

Best Answer

You have a syntax problem, try this :

Create Table If not exists CompanyRank
(
CID int, Year int, IndexYN int, SPRank int, FortuneRank int,
primary key (CID, Year), index (CID), Index(year),
foreign key (CID) references CompanyInfo (CID),
foreign key (Year) references TimePeriod (Year)
) engine = innodb;

the reference is "CompanyInfo (CID)", not "CompanyInfo.CID"