Reputation: 384
I have a table which has these columns:
Id
(Primary Key): the id.OwnerId
(Foreign Key): the id of the owner, which resides in another table.TypeId
(Foreign Key): the type of thing this record represents. There are a finite number of types, which are represented in another table. This links to that table.TypeCreatorId
(ForeignKey): the owner of the type represented by TypeId.SourceId
(Foreign Key): this isn't important to this question.I need to constrain this table such that for each Id, there can be only one of each TypeCreatorId. I hope that makes sense!
Upvotes: 0
Views: 46
Reputation: 21047
Simply create a unique index on OwnerId
and TypeCreatorId
.
An example using MySQL (sorry, I don't use SQL Server):
alter table yourTable
add unique index idx_newIndex(OwnerId, TypeCreatorId);
Example. I'll just put here what would happen with this new unique index:
OwnerId | TypeCreatorId
--------+--------------
1 | 1
1 | 2 -- This is Ok
2 | 1 -- Ok too
2 | 2 -- Ok again
1 | 2 -- THIS WON'T BE ALLOWED because it would be a duplicate
Upvotes: 1
Reputation: 754518
For SQL Server, you have two options:
create a UNIQUE CONSTRAINT
ALTER TABLE dbo.YourTable
ADD CONSTRAINT UNIQ_Id_TypeCreator UNIQUE(Id, TypeCreatorId)
create a UNIQUE INDEX
:
CREATE UNIQUE INDEX UIX_YourTable_ID_TypeCreator
ON dbo.YourTable(Id, TypeCreatorId)
Basically, both things achieve the same thing - you cannot have two rows with the same (Id, TypeCreatorId)
values.
Upvotes: 2