2017-05-24 63 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 –