Skip to content Skip to sidebar Skip to footer

Unique Key Across Multiple Tables

Rewrote the question: I have three tables, objects, owners and objectOwnerRelation objects has three columns: id, name, type owners has two columns: id, owner objectOwnerRelation h

Solution 1:

There is no way to enforce the constraint:

Two objects can have the same name and type but only if the owner is different.

using only declarative referential integrity (DRI). Using just DRI you could create a table that contains all of the columns that you need to build a unique key. You could denormalize object.name and object.type to your objectOwnerRelation table. This would ensure that there are no records in objectOwnerRelation with the same name and type and owner but only in the intersection table itself.

At the end of the day, DRI does not allow a child table to impose a constraint on a parent.

The constraint that you are looking for needs to be imposed procedurally, using a trigger or some other code.

Solution 2:

You have to change the structure of objectOwnerRelation

ownerid, objectid and PK on both

You can leave the structure as it is and add a UNIQUE INDEX on ownerid and objectid but each row can be identified through ownerid and objectid

Solution 3:

That means that two objects with the same name and type can't appear in the objectOwnerRelation with the same ownerId.


An object can have multiple owners and a owner can have multiple objects.


These two sentences make it quite simple actually, the main problem is the sentence that somehow implies that objects can change names depending on the owner -- hence Joel's answer.

So here is the simple solution

enter image description here


Now the troublesome sentence

Two objects can have the same name and type but only if the owner is different.

Does this mean that objects can be renamed? That their types can be renamed/changed by an owner?

So -- as you see -- the main problem here is that your question can be (mis)interpreted in many ways.

<rant>

Technically, this design encountered a problem on the conceptual level, way before it reached entities (logical level) and tables (physical level). Evan small changes on the conceptual level of design can create huge differences on logical and physical levels -- as obvious from submitted answers and comments to your post.

</rant>

Solution 4:

In you question it looks like combination of table name and type are needs to be unique per objectownerid.

My recommendation is to add ownerID to objects and create unique index on ([name],[type],[ownerid]), this way you can enforce you constraint.

Another solution which will allow to keep current structure is to create trigger on the table that constraint should be enforced on, do the checks and rollback in case of constraint violation.

Post a Comment for "Unique Key Across Multiple Tables"