在更新查询期间根据其新值更新另一列

时间:2017-02-02 21:14:49

标签: php mysql sql sql-update

我有一个名为item_quantity的表,其中包含2个字段,数量和请求。我有一个查询,每次客户购买时都会更新字段数量。问题是我想在数量变为0时将请求的列更新为0.这是我到目前为止所尝试的。

UPDATE `item_quantity`SET `quantity`=quantity-5,`requested`= CASE when `quantity` = 0 then 0 else 1 end where `item_id`=1;

但是案件的下划线是红色的。我不知道它的语法或逻辑错误。我该怎么做?先感谢您! [This is what i got] 1

2 个答案:

答案 0 :(得分:1)

您可以在设置item_quantity后执行请求的更新。然后你可以像这样直接比较item_quantity:

UPDATE `item_quantity`
SET
  `quantity`= `quantity` - 5
  ,`requested`= IF(`quantity` = 0, 0, `requested`);

<强>样品

mysql> SELECT * FROM item_quantity;
+----+----------+-----------+
| id | quantity | requested |
+----+----------+-----------+
|  1 |       10 |         9 |
+----+----------+-----------+
1 row in set (0,00 sec)

mysql> UPDATE `item_quantity`
    -> SET
    ->   `quantity`= `quantity` - 5
    ->   ,`requested`= IF(`quantity` = 0, 0, `requested`);
Query OK, 1 row affected (0,00 sec)
Rows matched: 1  Changed: 1  Warnings: 0

mysql> SELECT * FROM item_quantity;
+----+----------+-----------+
| id | quantity | requested |
+----+----------+-----------+
|  1 |        5 |         9 |
+----+----------+-----------+
1 row in set (0,00 sec)

mysql> UPDATE `item_quantity`
    -> SET
    ->   `quantity`= `quantity` - 5
    ->   ,`requested`= IF(`quantity` = 0, 0, `requested`);
Query OK, 1 row affected (0,00 sec)
Rows matched: 1  Changed: 1  Warnings: 0

mysql> SELECT * FROM item_quantity;
+----+----------+-----------+
| id | quantity | requested |
+----+----------+-----------+
|  1 |        0 |         0 |
+----+----------+-----------+
1 row in set (0,00 sec)

mysql>

答案 1 :(得分:0)

您可以使用BEFORE UPDATE触发器。 此触发器将在更新执行之前触发,您可以更新其他字段。 请尝试以下方法:

CREATE TRIGGER item_quantity_before_update
BEFORE UPDATE
   ON item_quantity FOR EACH ROW
BEGIN
   DECLARE old_quantity NUMBER;
   DECLARE new_quantity NUMBER;

   SELECT quantity INTO old_quantity;

   SET new_quantity = old_quantity - 5;
   IF new_quantity == 0 THEN
      SET new.requested = 0
   ELSE
      SET new.requested = 1;
   END IF;
END; //