首页 > 事务处理速度太快导致数据出错?

事务处理速度太快导致数据出错?

有两个 MySQL 数据库表 a 和 b
a 有一个整型字段 a_count(此字段某些情况下归0)
b 有一个整型字段 b_count

事务处理:

  1. select 表 a,得到 a_count,然后计算 count = a_count + 1

  2. update 表 a,a_count = count

  3. insert 一条记录到表 b,b_count = count

想实现的的情况 count:1 2 3 4 5 6 7 1 2 3 4 5 6(第二个1是因为a_count归零了)
得到的真实情况 count:1 2 2 2 3 3 4 1 1 2 3 3 3(操作的速度太快导致数据重复)

问题一:有什么方式可以解决这样的问题?(加锁解决:http://docs.sequelizejs.com/en/latest/api/transaction/#lock)
问题二:解决了第一个问题,如果我想限制一个时间内(如:一秒)只能一次操作有哪些方式?

------------更新分割线----以下2016/04/23更新------------

上代码(语言 Node.js,用得 orm 是 sequelize)

models.sequelize.transaction(function (t) {
  
  // 查询表a数据
  return models.A.findOne({
    where: {
      id: user_id,
    },
    transaction: t,
  }).then(function (a) {
    
    var count = a.a_count + 1;
    
    // 事务:新增表b记录
    return models.B.create({
      b_count: count,
    }, {transaction: t}).then(function () {
      
      // 事务:更新表a数据
      return models.A.update({
        a_count: count,
      }, {
        where: {
          id: user_id,
        },
        transaction: t,
      }).then(function () {
        res.json({success: 'success'});
      });
    });
  });
});

楼主你好逗,处理太快导致???


第一个问题:加锁解决:http://docs.sequelizejs.com/en/latest/api/transaction/#lock


按照上面的描述,事务2对问题并没有什么影响。而且就单纯的看事务1,并看不出什么问题。我想是不是你的业务代码造成了数据更新出错,而并不是mysql事务的锅。


线程没同步?

【热门文章】
【热门文章】