Mysql

將多個外鍵添加到單個表

  • April 10, 2019

我正在嘗試將多個外鍵添加到同一個表中;但是,錯誤程式碼1215:無法添加外鍵約束不斷彈出。我已經閱讀了其他人關於同一主題的文章並嘗試添加 innodb,但錯誤仍然彈出。任何幫助表示讚賞!

這是我的程式碼:

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;

你有語法問題,試試這個:

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;

參考是“CompanyInfo (CID)”,而不是“CompanyInfo.CID”

引用自:https://dba.stackexchange.com/questions/146179