MySQL FOREIGN KEY错误,ON DELETE CASCADE

时间:2015-06-07 18:52:02

标签: mysql sql foreign-keys ddl

我完全不知道为什么MySQL遇到第二个CREATE TABLE语句的问题。

CREATE TABLE User(
    uid INTEGER, 
    url CHAR(100),
    firstname CHAR(40),
    lastname CHAR(40),
    PRIMARY KEY(uid)
);

以下是导致问题的原因:

CREATE TABLE Follows(
    uid INTEGER,
    url CHAR(100),
    PRIMARY KEY(uid,url),
    FOREIGN KEY(uid) REFERENCES User(uid), ON DELETE CASCADE,
    FOREIGN KEY(url) REFERENCES User(url), ON DELETE CASCADE
    );

我得到的错误是:

  

#1064 - 您的SQL语法出错;检查与MySQL服务器版本对应的手册,以便在第1行的“ON DELETE CASCADE,FOREIGN KEY(url)REFERENCES User(url),ON DELETE CASCADE”附近使用正确的语法

3 个答案:

答案 0 :(得分:1)

这里有一些问题:

首先on delete cascade是外键定义的一部分,因此应该删除之前的逗号(,)。

其次,第二个外键引用url,它不是唯一键,因此不允许。所以要么删除这个约束:

CREATE TABLE Follows (
    uid INTEGER,  
    url CHAR(100),  
    PRIMARY KEY(uid,url),  
    FOREIGN KEY(uid) REFERENCES User(uid) ON DELETE CASCADE
);

或者在url上定义另一个唯一键:

CREATE TABLE User(
    uid INTEGER, 
    url CHAR(100),
    firstname CHAR(40),
    lastname CHAR(40),
    PRIMARY KEY(uid),
    UNIQUE (url)
);


CREATE TABLE Follows (
    uid INTEGER,  
    url CHAR(100),  
    PRIMARY KEY(uid,url),  
    FOREIGN KEY(uid) REFERENCES User(uid) ON DELETE CASCADE,
    FOREIGN KEY(url) REFERENCES User(url) ON DELETE CASCADE
);

答案 1 :(得分:0)

尝试在REFERENCES后删除用户(uid)和参考用户(url)这个","

答案 2 :(得分:0)

你必须在User(uid)ON DELETE CASCADE之后加上一个空白,你也应该写入查询的末尾,如下所示:engine =' innodb&#39 ;;

我的意思是在最后一个)和;