我正在努力做到这一点:
$articles_id = 105; // comes from argument
$type = 'units_out'; // comes from argument
$quantity = 4; // comes from argument
$date = date('Y-m-d');
$sql = "INSERT INTO stock (articles_id, date, units_in, units_out)
VALUES (?, ?, ?, ?)
ON DUPLICATE KEY UPDATE $type = IF(VALUES($type) - $quantity >= 0, VALUES($type) - $quantity, 0)";
$res = $this->db->query($sql, array($articles_id, $date, 0, $quantity));
该记录已存在,因此会进行更新。 BD中 units_out 的初始值为 2 ,其 UNSIGNED MEDIUMINT 字段。因此,因为它是无符号类型,2 - 4 = -2,对于UNSIGNED MEDIUMINT意味着从其最大值开始向下计数。
查询后, units_out = 16777215 。我想通过使用MySQL的 VALUES()函数来避免这种行为,但如果我将它与bd-> query()
一起使用它就无法正常工作我已经尝试过在PHPMyAdmin中直接执行它并确实有效, units_out 会导致 0 。为什么这不适用于Codeigniter?
答案 0 :(得分:1)
在if,(VALUES($ type)> $数量)中再添加一个条件,例如
$sql = "INSERT INTO stock (articles_id, date, units_in, units_out)
VALUES (?, ?, ?, ?)
ON DUPLICATE KEY UPDATE $type = IF((VALUES($type) > $quantity) and (VALUES($type) - $quantity >= 0), VALUES($type) - $quantity, 0)";
或者只是添加大于条件而不是检查减法> 0
$sql = "INSERT INTO stock (articles_id, date, units_in, units_out)
VALUES (?, ?, ?, ?)
ON DUPLICATE KEY UPDATE $type = IF(VALUES($type) >= $quantity, VALUES($type) - $quantity, 0)";