为什么在违反唯一键约束而不是主键约束时

为什么在违反唯一键约束而不是主键约束时

本文介绍了为什么在违反唯一键约束而不是主键约束时,MySQL中会出现自动增量间隔?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道在MySQL中使用INSERT ... ON DUPLICATE KEY UPDATE时,插入失败时会出现自动增量间隔.但是-我注意到,只有在违反唯一键约束的情况下才会出现这种差距.如果主键约束失败,则不会出现自动增量间隔.

I understand that when using INSERT ... ON DUPLICATE KEY UPDATE in MySQL there are auto increment gaps when an insert fails. However -- I've noticed that the gaps only occur when a unique key constraint is violated. If the primary key constraint fails, no auto increment gap occurs.

这两者之间有什么区别的原因是什么?

What's the reason for the difference between the two?

谢谢!

推荐答案

如果自动增量字段是主键,则只有当您在insert语句中将自动增量字段的值显式设置为时,主键中的重复项才会发生该字段中已经存在的值(您为什么要这样做超出我的范围).

If the auto increment field is the primary key, then duplication in the primary key can only happen if you explicitly set the auto increment field's value in the insert statement to an already existing value in that field (why you would do this is beyond me).

作为使用自动增量上的mysql文档说:

要点是,在这种情况下,mysql不会尝试为自动增量列生成值,而是将使用插入中指定的值.此外,该序列还将在该字段中重置为最大值,因此下一个插入片段将没有任何间隙.

The point is, that in this case mysql does not try to generate a value for the auto increment column, but will use the value specified in the insert. Moreover, the sequence is also reset to the max value in the field, therefore the next insert will not have any gaps.

但是,如果在尝试插入时另一个唯一索引约束失败,则mysql已经为自动增量字段生成了值,因此在自动增量序列中会创建一个间隔.

However, if another unique index constraint fails when you attempt the insert, then mysql has already generated the value for the auto increment field, therefore a gap is created in the auto increment sequence.

这篇关于为什么在违反唯一键约束而不是主键约束时,MySQL中会出现自动增量间隔?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-05 02:32