0

I seven columns in my MySQL table. Four of these are called A B C D.

Assume that I already have values 1 ,2 ,3 ,4. How can I prevent a duplicate combination from being added.

3 Answers 3

2

Why don't you simply make a unique key for A, B, C, D

ALTER TABLE <tablename> ADD UNIQUE KEY (A, B, C, D);
Sign up to request clarification or add additional context in comments.

4 Comments

I might be reading the question wrong, but this only works if you want a single A=1, A=2, etc; a single B=1, B=2, etc. However, if you want only unique combinations, like "A=1 and B=2 and C=3 and D=4", this won't work. Because then "A=1, B=2, C=3, D=4" would be different from "A=1, B=2, C=1, D=1", but it won't be allowed because there already was a B=2.
@Alec: A composite unique constraint means that all the values (four in this case) make up a distinct value. IE: if 1, 1, 1, 1 exists - the second attempt to add or update a row to 1,1,1,1 will return an error. But 1,2,1,1 and 1,1,2,1 would work...
@OMG Ponies, nice. Didn't know that was possible :)
@rich kid: you can enter that statement as it is for an existing table. It will fail if there are already multiple values for a,b,c,d. Then you will have to remove them first. @Alec: the combination of the 4 fields must be unique, not each individual field.
0

In MySql, you can create a unique key that is a combination of several columns.

ALTER TABLE <nameOfTable> ADD UNIQUE KEY (A, B, C, D);

However it should be noted that there could be a large performance impact if these fields are storing text or other long values.

Comments

-1

You can set a MySQL field to UNIQUE, but not a combination of fields, as far as I know.

So, first do a simple query to see if the combination A=1, B=2, C=3, D=4 already exists. If not, add it, otherwise prompt the user with an error.

1 Comment

MySQL supports composite UNIQUE key constraints: dev.mysql.com/doc/refman/5.1/en/alter-table.html

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.