简体   繁体   English

复合唯一约束SQL

[英]Composite Unique Constraint SQL

I have a table with parents and children, each record has a PRIMARY KEY id, a 'name', and a 'parent' that references another record's 'id'. 我有一个包含父母和孩子的表,每个记录都有一个PRIMARY KEY id,一个'name'和一个引用另一个记录'id'的'parent'。

Can I enforce UNIQUE constraint on the 'name' among records that share a 'parent'? 我可以在共享“父”的记录中对“名称”强制执行UNIQUE约束吗?

Yes. 是。 This would be a composite unique key: 这将是一个复合唯一键:

alter table t add constraint unq_t_parent_name unique (parent, name);

If you don't care if the constraint has a name, then you can just create a unique index: 如果您不关心约束是否有名称,那么您只需创建一个唯一索引:

create unique index unq_t_parent_name on t(parent, name);

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

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