MySQL composite unique on FK's

六眼飞鱼酱① 提交于 2019-12-09 01:45:39

问题


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.



来源:https://stackoverflow.com/questions/2591477/mysql-composite-unique-on-fks

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!