简体   繁体   中英

Can't create table with foreign key - MySQL Error 150

I'm having some trouble understanding why I'm getting MySQL code error 150 for the following snippet:

-- Exercise Categories
CREATE TABLE Exercise_cat
(
ec_id       INT NOT NULL AUTO_INCREMENT,
name        VARCHAR(25),
PRIMARY KEY (ec_id)
);
-- This inserts fine

-- Exercise Descriptions
CREATE TABLE Exercise_desc
(
e_id        INT NOT NULL AUTO_INCREMENT,
name        VARCHAR(25),
ec_id       INT NOT NULL,
cal_per_hour    INT NOT NULL,
PRIMARY KEY (e_id),
FOREIGN KEY (ec_id) REFERENCES Excercise_cat(ec_id)
);
-- ERROR (foreign key constraint not formed)

I didn't leave off the column name, as in [1] [2] .
I have semicolons, as MySQL wants me to.

How would I fix my foreign key so that I can create the table?

you mean Exercise_cat not Excercise_cat

CREATE TABLE Exercise_desc
(
    e_id        INT NOT NULL AUTO_INCREMENT,
    name        VARCHAR(25),
    ec_id       INT NOT NULL,
    cal_per_hour    INT NOT NULL,
    PRIMARY KEY (e_id),
    FOREIGN KEY (ec_id) REFERENCES Exercise_cat(ec_id)
);

The table you are referencing Excercise_cat does not exists . But Exercise_cat exists.

So the following line should be corrected.

FOREIGN KEY (ec_id) REFERENCES Excercise_cat(ec_id)
                                 ^
                                 |
                                 +-- Remove this extra 'c'

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