【问题标题】:Is there some effects on table's id index if error occured in transaction?如果事务中发生错误,对表的 id 索引是否有影响?
【发布时间】:2019-03-28 11:05:03
【问题描述】:

这是我在 Yii 1.1 中的主要交易代码:

try{
     $transaction=Yii::app()->projectdb->beginTransaction();
     foreach($list as $order){
         $orderInfo = OrderInfo::model()->findByPk($order['order_id']); 
         if(empty($orderInfo )){
             throw new Exception('Empty order_info');
          }
       // ...
       // save order data into mysql

         }
      $transaction->commit();

   }catch (Exception $e){
       $transaction->rollBack();
    }

现在,我发现我的表格顺序中缺少 id,

select id from order where id between 10231 and 10280

# id      name 
# 10231   name_10231
# 10280   name_10280

# missed 50 data

这和上面的交易代码有关系吗?当事务中发生错误时,它会添加 id 的索引?

如果你能给我一个明确的答案,非常感谢..

【问题讨论】:

    标签: php mysql yii


    【解决方案1】:

    是的,它可能与回滚事务有关。如果您在事务期间插入新记录,MySQL 会为该记录保留 ID(增加AUTO_INCREMENT 计数器,因此不同进程可以在此事务期间插入记录而没有 ID 冲突的风险)。如果您回滚事务,此 ID 将不会被重用。所以如果你:

    1. 打开交易,
    2. 插入 50 条记录,
    3. 回滚事务,

    您最终会在 IDs 列中出现空白,因为这 50 个 ID 被保留,但从未提交。

    【讨论】:

    • 感谢您的回复,更多问题。错误发生的地方有什么不同吗?我的意思是如果错误发生在model->save()操作之前,我抓住它并回滚,它仍然有auto_increase的ID吗?
    • 不,计数器增加了INSERT查询,这是在save()内部执行的。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-12-20
    • 2012-10-13
    • 2018-02-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多