MySQL composite unique on FK's

2020-03-06 03:46发布

问题:

I want to implement the following constraints in mysql:

create table TypeMapping(
    ...
    constraint unique(server_id,type_id),

    constraint foreign key(server_id) references Server(id),

    constraint foreign key(type_id) references Type(id)
);

This throws a 'ERROR 1062 (23000): Duplicate entry '3-4' for key 'server_id'' when I issue an insert/update that would break the constraint. Is this type of constraint even possible? If so how? Thank you.

回答1:

Yes, that is perfectly valid. Make sure you understand that the composite unique constraint will only break when you try to insert a new row in TypeMapping, where another row with the same server_id and type_id already exists.