Foreign key in MySql as composite primary key
Asked Answered
B

2

5

I have the database with the name Shop with this 3 tables:

create table usr(
    id_usr varchar(20) not null,
    primary key(id_usr)

);

create table product(
    id_product varchar(20) not null,
    id_size varchar(20) not null,
    price float(4,2) unsigned,
    primary key(id_product,id_size)
);

create table cart(
    myUser varchar(20), 
    mySize varchar(20),
    product varchar(20),
    qty int not null,
    primary key(myUser,product,mySize),
    FOREIGN KEY (myUser) REFERENCES usr (id_usr),
    FOREIGN KEY (product) REFERENCES product (id_product),
    FOREIGN KEY (mySize) REFERENCES product (id_size)
);

when I compile in sql, it gives to me this message:

1005 - Can't create table 'Shop.cart' (errno: 150)

If I try to delete the foreign key mySize (FOREIGN KEY (mySize) REFERENCES prodotto (id_size)) it works, why have I this message?

Bobbee answered 20/5, 2014 at 21:4 Comment(1)
Where is your prodotto table?Drying
M
6

You're making a FK reference to product table but defining only part of the key. Try...

FOREIGN KEY (product, mySize) REFERENCES product (id_product, id_size),
Mal answered 21/5, 2014 at 7:10 Comment(0)
D
2

My guess is you haven't created your prodotto table yet. This works:

create table user(
    id_user varchar(20) not null,
    primary key(id_user)

);

create table product(
    id_product varchar(20) not null,
    id_size varchar(20) not null,
    price float(4,2) unsigned,
    primary key(id_product,id_size)
);

create table prodotto (
  id_size varchar(20) primary key
);

create table cart(
    myUser varchar(20), 
    mySize varchar(20),
    product varchar(20),
    qty int not null,
    primary key(myUser,product,mySize),
    FOREIGN KEY (myUser) REFERENCES user (id_user),
    FOREIGN KEY (product) REFERENCES product (id_product),
    FOREIGN KEY (mySize) REFERENCES prodotto (id_size)
);
Drying answered 20/5, 2014 at 21:8 Comment(1)
I wronged to write, because I did a translation of my db to make it more easy to understand and I forgot to translate prodottoBobbee

© 2022 - 2024 — McMap. All rights reserved.