简体   繁体   中英

Crafting a Check Constraint that Depends on Another Table

I'm working in Oracle. I've got two tables, a master table with an ID columns and a detail table, with an ID column, a foreign key to the master table and a name column.

MASTER
--------
ID

formatting break

DETAIL
-------------
ID
MASTER_ID
NAME

I want all the child details of a given master to have unique names. Name is not unique among the details, though. Two details with different masters may have the same name.

I think I can do this with a check constraint, but I'm struggling with how to phrase it.

It doesn't sound like you want a check constraint. It sounds like you want a unique constraint

alter table detail_table
  add constraint name_uniq_within_master unique( master_id, name );

That would prevent you from having two rows with the same name and master_id but would allow rows with the same name and different master_id values.

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.

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