在yii中的mysql中获得一个带有maxid和condition的记录,但有时它会获得第二个记录


Get a record with maxid and condition in mysql in yii, but sometime it get second record?

我的表:

CREATE TABLE IF NOT EXISTS `the_kho_chi_tiet_with_id` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `ngay_thang` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
  `ma_phieu` varchar(100) COLLATE utf8_unicode_ci NOT NULL,
  `id_san_pham` int(11) NOT NULL,
  `id_kho` int(11) NOT NULL,
  `khoi_luong_nhap` double NOT NULL,
  `so_luong_nhap` int(11) NOT NULL,
  `khoi_luong_xuat` double NOT NULL,
  `so_luong_xuat` int(11) NOT NULL,
  `khoi_luong_ton` double NOT NULL,
  `so_luong_ton` int(11) NOT NULL,
  `kho_du_tru` int(11) NOT NULL DEFAULT '0',
  PRIMARY KEY (`id`)
)

PHP代码:

$sql = "SELECT so_luong_ton, khoi_luong_ton, kho_du_tru FROM the_kho_chi_tiet_with_id WHERE id_kho = $id_kho and id_san_pham = $id_san_pham ORDER by id DESC LIMIT 1";
$command=$connection->createCommand($sql);
$dataReader=$command->queryAll();
if($dataReader!=null)
{
    foreach($dataReader as $row)
    {
       .................
    }
}
**Get a record with maxid and condition in mysql in yii, *but sometime it get second record* !?**
  Please check with the below, hope it works!..if not please tell...
  $id_kho=373;//sample value declaration
  $id_san_pham=1;//sample value declaration
  $select="select max(id) as id,so_luong_ton, khoi_luong_ton, kho_du_tru from  
               the_kho_chi_tiet_with_id where users_ref_id=".$id_kho." and   
          status=".$id_san_pham;
  $command = Yii::app()->db->createCommand($select)->queryRow(); 
  $Maxid=$command['id'];
  $so_luong_ton=$command['so_luong_ton'];
  $khoi_luong_ton=$command['khoi_luong_ton'];
  $kho_du_tru=$command['kho_du_tru'];

我认为,问题在于冲突。这意味着当我得到记录有max_id时,然后在插入新记录之前,让另一个进程插入新记录。如果发生这样的情况,那么如何处理来解决上述问题呢?

我的解决方案:

$lock = $connection->createCommand('LOCK TABLES `the_kho_chi_tiet_with_id` READ');
$lock->execute();
$sql = "SELECT so_luong_ton, khoi_luong_ton, kho_du_tru FROM the_kho_chi_tiet_with_id WHERE id_kho = $id_kho and id_san_pham = $id_san_pham ORDER by id DESC LIMIT 1";
$command=$connection->createCommand($sql);
$dataReader=$command->queryAll();
if($dataReader!=null)
{
    foreach($dataReader as $row)
    {
       .................
    }
}
//Insert new record here
TheKhoChiTietWithId::model()->InsertNewRecord(1,300,1,333,1);
$unlock = $connection->createCommand('UNLOCK TABLES');
$unlock->execute();

我锁定该表,以便不将其他会话工作保留到此表。