2017-02-02 287 views
0

我有一個名爲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

回答

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> 
+0

我試過,但從IF開始,以分號總是紅色下劃線。我猜我的語法錯了。我如何解決它?它只是說意想不到的標記 – healer

+0

@healer - 您能否請您發佈您的查詢 –

+0

@healer - 您的查詢中必須有錯字。我在我的回答中添加了一個示例 –

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; //