MySQL错误1005错误150外键约束形成错误

时间:2015-12-03 19:40:41

标签: mysql

我创建了以下表格:

停止:

CREATE TABLE Stop (  
 routeNo        DECIMAL (4,0) UNSIGNED,  
 stopNo         DECIMAL(3,0) UNSIGNED,  
 latitude       DECIMAL(19,16),  
 longitude      DECIMAL(19,16),  
 CONSTRAINT PK_Location PRIMARY KEY (routeNo, stopNo),  
 CONSTRAINT FK_stop_location FOREIGN KEY (latitude,longitude) REFERENCES Location(latitude,longitude),  
 CONSTRAINT FK_stop_route FOREIGN KEY (routeNo) REFERENCES Route(routeNo)  
);  

表格WorkDay:

CREATE TABLE Workday (
 theDate    DATE    PRIMARY KEY,
 notes  VARCHAR(30)
);  

然后我尝试使用以下代码创建订单交付表:

CREATE TABLE OrderDelivery 
(
 routeNo DECIMAL(4,0) UNSIGNED,
 stopNO DECIMAL(3,0) UNSIGNED, 
 orderNo INT(9),
 CONSTRAINT pk_Orders PRIMARY KEY (routeNo, stopNo, orderNo),
 deliveryDateExpected DATE, 
 deliveryTime TIME,
 customerName VARCHAR(40),
 creditCardNo CHAR(16) NOT NULL,
 customerRanking ENUM('platinum','gold','occasional','one-off'),
 CONSTRAINT fk_Routes FOREIGN KEY (routeNo) REFERENCES Stop(routeNo),
 CONSTRAINT fk_Stops FOREIGN KEY (stopNo) REFERENCES Stop(stopNo),   
 CONSTRAINT fk_Dates FOREIGN KEY (deliveryDateExpected) REFERENCES Workday(theDate)
);

但每次我尝试创建OrderDelivery表时,都会给出错误形成外键的错误

"SQL Error (1005): Can't create table 'harry.OrderDelivery' (errno:150)Foreign key constraint is incorrectly formed"

我如何纠正这个问题?

1 个答案:

答案 0 :(得分:0)

您无法创建具有多个主键的表的外键,该主键仅引用该主键的一个字段。

所以你的问题就在这里:

CONSTRAINT fk_Routes FOREIGN KEY (routeNo) REFERENCES Stop(routeNo),
CONSTRAINT fk_Stops FOREIGN KEY (stopNo) REFERENCES Stop(stopNo),  

您应该将其更改为

 CONSTRAINT fk_Stops_Routes 
    FOREIGN KEY (routeNo, stopNo) 
    REFERENCES Stop(routeNo, stopNo),

或者根据您的要求,您必须更改模型以满足您的需求。