2015-12-22 135 views
1

我在我的SQL中面临外键错误。我的mySQL表是作为主键错误的mysql外键

create table if not exists table1(
cust_name varchar(30) not null, 
cust_phone char(16) not null, 
cust_mail char(30) not null, 
cust_address varchar(100), 
bills int(10), 
primary key (cust_name) 
)ENGINE=INNODB; 

create table if not exists table2 (
camp_id varchar(30) not null, 
advr_id varchar(30) not null, 
foreign key (advr_id) references table1 (cust_name), 
primary key (camp_id) 
)ENGINE=INNODB; 

create table if not exists table3(
ad_id varchar(30) not null, 
camp_id varchar(30) not null, 
foreign key (camp_id) references table2(camp_id), 
primary key (ad_id) 
)ENGINE=INNODB; 

create table if not exists counter(
ad_id varchar(30) not null, 
foreign key (ad_id) references table3(ad_id), 
PRIMARY KEY(ad_id) 
)ENGINE=INNODB; 

当我运行上面的命令,我得到follwoing错误。在线路96

ERROR 1215(HY000):无法添加外键约束

问题是什么?

+0

在[sqlfiddle](http://sqlfiddle.com/#!9/224f5) –

+0

上执行没有任何问题尝试从表counter中除去'ad_id varchar(30)not null'。 – MASh

+0

@Shafiq你应该首先检查表中的数据,可能会造成问题。 –

回答

0

没有任何错误,当我运行此代码。我认为他们可能是你的原始代码中的一些拼写错误。尝试使用mysql gui应用程序获取日志的详细信息。它会精确地指出错误。

+0

谢谢,这是我发现的问题,它只是一个拼写(姓名)错误 – Shafiq

1

没有任何错误。这是运行没有错误。

mysql> create table if not exists table1(
    -> cust_name varchar(30) not null, 
    -> cust_phone char(16) not null, 
    -> cust_mail char(30) not null, 
    -> cust_address varchar(100), 
    -> bills int(10), 
    -> primary key (cust_name) 
    ->)ENGINE=INNODB; 
Query OK, 0 rows affected, 1 warning (0.08 sec) 


mysql> create table if not exists table2 (
    -> camp_id varchar(30) not null, 
    -> advr_id varchar(30) not null, 
    -> foreign key (advr_id) references table1 (cust_name), 
    -> primary key (camp_id) 
    ->)ENGINE=INNODB; 
Query OK, 0 rows affected, 1 warning (0.10 sec) 


mysql> create table if not exists table3(
    -> ad_id varchar(30) not null, 
    -> camp_id varchar(30) not null, 
    -> foreign key (camp_id) references table2(camp_id), 
    -> primary key (ad_id) 
    ->)ENGINE=INNODB; 
Query OK, 0 rows affected (0.37 sec) 


mysql> create table if not exists counter(
    -> ad_id varchar(30) not null, 
    -> foreign key (ad_id) references table3(ad_id), 
    -> PRIMARY KEY(ad_id) 
    ->)ENGINE=INNODB; 
Query OK, 0 rows affected (0.42 sec) 

我执行我的数据库,但没有任何错误或警告