简体   繁体   English

sql独特的复合外键

[英]sql unique composite foreign key

I have 2 tables: 我有2张桌子:

group_config (id_group_config, owner_id, name_group_config)

group (id_group, id_group_config, name_group) - id_group_config is FK to group_config

So basically, a user (owner_id) creates a group_config, then creates a group which references this group_config. 因此,基本上,用户(owner_id)创建了一个group_config,然后创建了一个引用该group_config的组。 Pretty standard, but I want a constraint that the name_group must be unique per owner_id. 相当标准,但是我想要一个约束,即每个owner_id的name_group必须唯一。

Only way I found to do this would be to replicate the owner_id on the group table too, which could cause inconsistencies. 我发现这样做的唯一方法是也要在组表上复制owner_id,这可能会导致不一致。

Am I missing something? 我想念什么吗?

thanks 谢谢

Since a group_config can't exist without owner_id You should make the PK of group_config a composite PK consisting of owner_id and group_config_id. 由于没有owner_id不能存在group_config,因此应将group_config的PK设置为由owner_id和group_config_id组成的复合PK。 You need to be careful about referential integrity constraints here eg what happens when you delete an owner? 您需要注意此处的参照完整性约束,例如,删除所有者时会发生什么?

This will automatically make the FK in group be that composite key. 这将自动使分组中的FK成为该组合键。

To make the name_group unique per owner in group table, you create a unique index composed of the columns owner_id and the name_group. 要使name_group在组表中按每个所有者唯一,您将创建一个由列owner_id和name_group组成的唯一索引。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM