I have a table and in that table i have a primary key, and a composite foreign key(combination of 2 foreign keys). I want to know how do I create a composite foreign key as unique which means that I don't want that composite foreign key duplicate again in the table?
this is the query for it
create table official_baby_toys(
official_baby_toys_id int,
baby_id int,
toy_id int,
toy_size_id,
primary key(official_baby_toys_id)
foreign key(baby_id,toy_id) references baby_toy(baby_id,toy_id),
foreign key(toy_size_id) references toy_size(toy_size_id),
)
First create two single foreign keys, then create the UNIQUE KEY with both fields:
create table official_baby_toys(
official_baby_toys_id int,
baby_id int,
toy_id int,
toy_size_id,
primary key(official_baby_toys_id)
foreign key(baby_id) references baby_toy(baby_id),
foreign key(toy_id) references baby_toy(toy_id),
foreign key(toy_size_id) references toy_size(toy_size_id),
unique key(baby_id, toy_id)
)
Also I don't know your DB schema, but I feel like baby_id
should actually reference to baby(baby_id)
rather than baby_toy(baby_id)
.
Edit: You can also create a composite foreign key, but you need to create index (or a primary key, which will also create an index) for these two fields first:
CREATE TABLE baby_toy (
# other field defs
baby_id int,
toy_id int,
primary key(baby_id, toy_id)
# OR index(baby_id, toy_id)
);
Then in the official_baby_toys
you should be able to create composite foreign key.
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.