MySQL FOREIGN KEY error, ON DELETE CASCADE

烈酒焚心 提交于 2019-12-25 04:31:32

问题


I have absolutely no clue why MySQL is having an issue with the second CREATE TABLE statement.

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

The below is the one that causes problems:

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
    );

Error I get is:

#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 'ON DELETE CASCADE, FOREIGN KEY(url) REFERENCES User(url), ON DELETE CASCADE)' at line 1


回答1:


There are a few issues here:

First the on delete cascade is part of the foreign key definition, so the comma (,) before it should be removed.

Second, the second foreign key references url, which is not a unique key, and therefore is not allowed. So either remove this constraints:

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

Or define another unique key on 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
);



回答2:


try to remove after REFERENCES User(uid) and REFERENCES User(url) this ","




回答3:


you have to put a gap after User(uid) ON DELETE CASCADE, also you should write in to the end of the query like this: engine='innodb';

i mean between the last ) and ;



来源:https://stackoverflow.com/questions/30697260/mysql-foreign-key-error-on-delete-cascade

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!