在外键约束表中添加外键

时间:2017-08-31 16:29:43

标签: mysql foreign-keys

我有这张表:

报价

+---------------------+-----------------------+------+-----+---------+---+
| Field               | Type                  | Null | Key | Default 
+---------------------+-----------------------+------+-----+---------+---+
| id                  | int(11) unsigned      | NO   | PRI | NULL    
... (More Columns)           
+---------------------+-----------------------+------+-----+-------------+

quotesPackagesInfo

+---------------+---------------------+------+-----+---------+------------+
| Field         | Type                | Null | Key | Default          
+---------------+---------------------+------+-----+---------+------------+
| id            | int(11) unsigned    | NO   | PRI | NULL     
| quoteId       | int(11) unsigned    | NO   |     | NULL    
... (More Columns)
+---------------+---------------------+------+-----+---------+------------+

quotesFlightsInfo

+---------------------------+---------------------+------+-----+----------+
| Field                     | Type                | Null | Key | Default 
+---------------------------+---------------------+------+-----+----------+
| id                        | int(11) unsigned    | NO   | PRI | NULL    
| quoteId                   | int(11) unsigned    | NO   | MUL | NULL                    
| packageId                 | int(11) unsigned    | YES  | MUL | NULL                                    ... (More Columns) 
+---------------------------+---------------------+------+-----+----------+

所以基本上有报价是主要的关键,在报价中有包裹后,包裹可以包含航班,所以我需要在删除包裹时,所有相关的航班都会被删除,所以我在航班上添加了一个外键,如下所示:

ALTER TABLE quotesFlightsInfo
ADD CONSTRAINT fk_quotesFlightsInfo_packageId
FOREIGN KEY (packageId) REFERENCES quotesPackagesInfo(id)
ON DELETE CASCADE

现在我试图向包中添加一个外键,所以当一个报价被删除时,包也会删除,所以航班但不起作用:(,这里是查询:

ALTER TABLE quotesPackagesInfo 
ADD CONSTRAINT fk_quotesPackagesInfo_quoteId 
FOREIGN KEY (quoteId) REFERENCES quotes(id) 
ON DELETE CASCADE

错误:无法添加或更新子行:外键约束失败(??????????#sql-312_2,CONSTRAINT fk_quotesPackagesInfo_quoteId FOREIGN KEY(quoteId)REFERENCES {{1 } {(quotes)ON DELETE CASCADE)

1 个答案:

答案 0 :(得分:0)

我删除了quotesPackagesInfo表并再次创建它从开始添加外键并且它工作,但仍然不知道什么是错误的