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:
If I try to delete the foreign key mySize (FOREIGN KEY (mySize) REFERENCES prodotto (id_size)) it works, why have I this message?
The Foreign key is a field that contains the primary key of some other table to establish a connection between each other. Let’s have a look at the syntax and different examples to create primary and foreign keys in MySQL. We can make a primary key on a segment of the table by utilizing the ALTER TABLE.
This is not possible. The foreign key can not refer to part of composite primary key of other table.
MySQL FOREIGN KEY Constraint. The FOREIGN KEY constraint is used to prevent actions that would destroy links between tables. A FOREIGN KEY is a field (or collection of fields) in one table, that refers to the PRIMARY KEY in another table. The table with the foreign key is called the child table, and the table with the primary key is called the ...
So I guess my question is, how do I relate these tables? do I have to to create foreign keys field in 'group' for each primary key in 'tutorial'? Per the mySQL documentation you should be able to set up a foreign key mapping to composites, which will require you to create the multiple columns.
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),
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)
);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With