简体   繁体   English

添加外键时出现MySQL#1064错误

[英]Mysql #1064 error while adding foreign key

I'm getting following error while i try to add foreign key to already created table by alter query as follows. 我在尝试通过alter query将外键添加到已创建的表中时遇到以下错误。 There is two table usertype which contain usertypeid field as primary key and account table which has usertypeid which i want to be a foreign key. 有两个表usertype,其中包含usertypeid字段作为主键,而帐户表则具有usertypeid,我想将其作为外键。

I'm using the following query, and as I know the query is correct, but don't know why i'm getting this error. 我正在使用以下查询,并且据我所知查询是正确的,但不知道为什么会收到此错误。

alter table account add constraint fk_usertypeid foreign key usertypeid references usertype(usertypeid) on update cascade on delete cascade;

Following error occured while i try to execute query 我尝试执行查询时发生以下错误

 #1064 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'references usertype(usertypeid) on update cascade on delete cascade' at line 1

I was getting error because index is not created on the field which is foreign key. 我收到错误消息是因为没有在外键字段上创建索引。

Don't know why but the foreign key required to be primary key, unique or a index must be created on it. 不知道为什么,但是必须在其上创建必须是主键,唯一键或索引的外键。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM