开发者

How can I prevent duplicate rows in MySql?

开发者 https://www.devze.com 2022-12-31 00:06 出处:网络
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

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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号