Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
707 views
in Technique[技术] by (71.8m points)

xampp - Can't create Foreign key on mysql database

I'm cannot create any foreign key in my mysql database. I used foreign key before, but recently I had to reformat and reinstall everything, and after a restored the mysql server, the foreign keys aren't working anymore.

I tried to create the simple tables bellow:

create table `order` (
    order_id int not null AUTO_INCREMENT primary key,
    customer varchar(100)
);

create table `order_item` (
    order_item_id int not null AUTO_INCREMENT primary key,
    order_id int not null,
    product varchar(100),
    foreign key (order_id) references `order`
);

The order tables is created successfully, but when i try to create the order_item table, i get the message Error Code: 1005. Can't create table mydb.order_item (errno: 150 "Foreign key constraint is incorrectly formed"). I've checked my code multiple times, and I'm not able to find a error. Do someone knows what could be wrong?

I'm using XAMPP to install and start both apache and mysql.


Edit: @LV98 's answer solved the error, but when i added a second Foreign key, got the same message:

create table `order` (
    order_id int not null AUTO_INCREMENT primary key,
    customer varchar(100)
);

create table product (
    product_id int not null auto_increment primary key,
    name varchar(100)
);

create table `order_item` (
    order_item_id int not null AUTO_INCREMENT primary key,
    order_id int not null,
    product_id int not null,
    product varchar(100),
    foreign key (order_id) references `order`(order_id),
    foreign key (product_id) references product (product_id)
);
question from:https://stackoverflow.com/questions/65926131/cant-create-foreign-key-on-mysql-database

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You forgot to reference a column.

foreign key (order_id) references `order`(order_id)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...