在yii中获取mysql中maxid和condition的记录,但有时会得到第二条记录?

时间:2014-10-29 08:12:22

标签: php mysql yii

我的表:

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* !?**

3 个答案:

答案 0 :(得分:0)

  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'];

答案 1 :(得分:0)

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

答案 2 :(得分:0)

我的解决方案:

$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();

我锁定表以保持此表没有其他会话工作。