ARW
ARW

Reputation: 3416

SQL Force one column to be unique for every row that shares the same foreign key

Just wondering if this can be enforced by the database or not...

I have a table that has a foreign key, and another column that needs to be unique across rows where the foreign key is the same. Duplicate entries are allowed as long as the foreign keys are different.

Is there a way to do this? I can't seem to figure out a way to set a unique constraint that is based on some condition rather than applied to the entire table.

Upvotes: 1

Views: 669

Answers (2)

John Woo
John Woo

Reputation: 263693

You can create UNIQUE constraint on both columns too.

ALTER TABLE myTableName 
      ADD CONSTRAINT tb_UQ UNIQUE (FKColumn, OtherColumn)

UPDATE 1

Upvotes: 1

Gordon Linoff
Gordon Linoff

Reputation: 1269563

You can add a unique constraint on two columns in MySQL:

alter table add unique index table(fk, othercolumn)

Upvotes: 1

Related Questions