简体   繁体   中英

SQL Error #1215 - Cannot add foreign key constraint

I have spent a good 3 hours searching for the answer to my problem (on here and google) and I cannot understand why I am getting this error after I try to add the "events" table.

Two tables:

    CREATE TABLE user (
            id INT NOT NULL AUTO_INCREMENT,
            u_name VARCHAR(32) NOT NULL,
            u_pass VARCHAR(32) NOT NULL,
            sub_status INT(3) NOT NULL,
            f_name VARCHAR(32),
            l_name VARCHAR(32),
            email VARCHAR(32),
            PRIMARY KEY(id, u_name, email)
    ) ENGINE=InnoDB;

    CREATE TABLE events (
        u_name VARCHAR(32) NOT NULL,
        event_name VARCHAR(32),
        event_date VARCHAR(32),
        comment VARCHAR(255),
        PRIMARY KEY(u_name, event_name),
        FOREIGN KEY(u_name) REFERENCES user(u_name)
        ON UPDATE CASCADE
        ON DELETE CASCADE
    ) ENGINE=InnoDB;

As far as I can see, there are no spelling errors, u_name is the exact same type between tables and it is a primary key in both tables.

mysql version is 5.6

Help is much appreciated and I thank you in advance. Let me know if there is any else I need to include.

EDIT: Turns out my queries do work, but on a different version of sql/mysql. jemz's answer works as well for a different version of sql.

CREATE TABLE `user` (
    `id` INT(11) NOT NULL AUTO_INCREMENT,
    `u_name` VARCHAR(32) NOT NULL,
    `u_pass` VARCHAR(32) NOT NULL,
    `sub_status` INT(3) NOT NULL,
    `f_name` VARCHAR(32) NULL DEFAULT NULL,
    `l_name` VARCHAR(32) NULL DEFAULT NULL,
    `email` VARCHAR(32) NOT NULL DEFAULT '',
    PRIMARY KEY (`id`, `u_name`, `email`),
    INDEX `u_name` (`u_name`)
)
COLLATE='latin1_swedish_ci'
ENGINE=InnoDB
;


CREATE TABLE `events` (
    `u_name` VARCHAR(32) NOT NULL,
    `event_name` VARCHAR(32) NOT NULL DEFAULT '',
    `event_date` VARCHAR(32) NULL DEFAULT NULL,
    `comment` VARCHAR(255) NULL DEFAULT NULL,
    PRIMARY KEY (`u_name`, `event_name`),
    CONSTRAINT `FK_events_user` FOREIGN KEY (`u_name`) REFERENCES `user` (`u_name`) ON UPDATE CASCADE ON DELETE CASCADE
)
COLLATE='latin1_swedish_ci'
ENGINE=InnoDB
;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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