How can I prevent duplicate rows in MySql?
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 开发者_C百科from being added.
Why don't you simply make a unique key for A, B, C, D
ALTER TABLE <tablename> ADD UNIQUE KEY (A, B, C, D);
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.
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.
精彩评论