更新时间:2023-02-02 21:57:59
您可以在这些列上创建一个多列索引并强制唯一性:请参见MySQL手册,网址为
You can simply create a multiple-column index on these columns and enforce uniqueness: see the MySQL manual at http://dev.mysql.com/doc/refman/5.0/en/multiple-column-indexes.html.
例如,在具有列id
(唯一主键),colA
和colB
的表中,运行:
For example, in a table with columns id
(unique primary key), colA
and colB
, you run:
ALTER TABLE table ADD UNIQUE KEY (colA,colB)
就是这样:在这两个列中导致重复条目的所有INSERT现在都将返回MySQL错误,而不是进行遍历.如果您使用INSERT IGNORE
,则如果执行它将违反此唯一约束,则不会引发MySQL错误,并且您的INSERT
语句将被忽略.
This is it: any INSERTs leading to a duplicate entry in these two columns combined will now return a MySQL error instead of going through. If you use INSERT IGNORE
, no MySQL error will be thrown if executing it would violate this unique constraint, and your INSERT
statement would be quietly disregarded.