2017-05-24 77 views
0

我有以下SQL脚本:无法添加外键

use restaurant; 
set foreign_key_checks=0; 
create table rtable_schedule(
    id int(11) not null, 
    rdate date not null, 
    start_hour tinyint, 
    start_min tinyint, 
    end_hour tinyint, 
    end_min tinyint, 
    foreign key (id,rdate) references rtable(id,reservation_date), 
    primary key (id,rdate) 
); 

然而,当我通过phpmyadmin的导入它,我得到以下错误:

#1215 - Cannot add foreign key constraint 任何想法如何能解决?请注意,rtable已存在

+0

'rtable'是否具有'id'和'reservation_date'作为组合主键? –

+0

不,它有ID作为主键 –

回答

1

Here's Foriegn Keys的MySQL文档,这就是它说的:

InnoDB permits a foreign key to reference any column or group of columns. However, in the referenced table, there must be an index where the referenced columns are listed as the first columns in the same order.

NDB requires an explicit unique key (or primary key) on any column referenced as a foreign key.

由于reservation_date列不是主键的一部分,所以很可能它在rtable中没有索引。我建议在创建Foreign Key表之前,在reservation_date列中创建一个索引。

+0

抱歉,但我是新来sql。你是什么意思创建索引? –

+0

https://dev.mysql.com/doc/refman/5.7/en/create-index.html –