SQL Error # 1215 - Unable to Add Foreign Key Constraint

I spent 3 hours looking for an answer to my problem (here and on Google) and I don't 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 same type between tables and it is the primary key in both tables.

mysql version is 5.6

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

EDIT: It turns out my queries are working, but on a different sql / mysql version. Jemz's answer also works for a different sql version.

+3


source to share


1 answer


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
;

      



+1


source







All Articles