我必须在MySQL数据库中找到下一个可用的id(如果数据库中有5个数据,我必须得到下一个可用的插入位置,即6).我怎样才能做到这一点?我已经使用过MAX(id),但是当我从数据库中删除一些行时,它仍然保留了未更新的旧最大值.
我正在使用Rails 4应用程序,该应用程序需要创建大量对象以响应来自其他系统的事件.当我调用我的某个模型时,我在主键列上遇到非常频繁的ActiveRecord::RecordNotUnique错误(由此引起PG::UniqueViolation)create!.
我在SO上找到了其他答案,建议救出异常并致电retry:
begin
  TableName.create!(data: 'here')
rescue ActiveRecord::RecordNotUnique => e
  if e.message.include? '_pkey' # Only retry primary key violations
    log.warn "Retrying creation: #{e}"
    retry
  else
    raise
  end
end
虽然这似乎帮助,我仍然得到吨的ActiveRecord::RecordNotUnique误差,对于已经存在于数据库(日志条目略)顺序ID:
WARN -- Retrying creation: PG::UniqueViolation: DETAIL: Key (id)=(3067) already exists.
WARN -- Retrying creation: PG::UniqueViolation: DETAIL: Key (id)=(3068) already exists.
WARN -- Retrying creation: PG::UniqueViolation: DETAIL: Key (id)=(3069) already exists.
WARN -- Retrying creation: PG::UniqueViolation: DETAIL: Key (id)=(3070) already …