2012-04-02 59 views
0

我在寫一個觸發器來更新另一個表上的AFTER INSERT表中的行。下面是表的腳本:無法從觸發器內的SELECT查詢中獲取值

inv_cost

CREATE TABLE inv_cost (
    Username varchar(20) NOT NULL DEFAULT '', 
    MachineType varchar(2) NOT NULL, 
    Cost smallint(4) NOT NULL DEFAULT '0', 
    PRIMARY KEY (Username,MachineType), 
) 

調查

CREATE TABLE investigation (
    Username varchar(20) NOT NULL, 
    MachineType varchar(2) NOT NULL 
) ENGINE=InnoDB DEFAULT CHARSET=latin1; 
DELIMITER ;; 
CREATE TRIGGER TRG1 AFTER INSERT ON investigation FOR EACH ROW BEGIN 
    DECLARE cost INT DEFAULT 0; 
    SET cost = (SELECT Cost FROM inv_cost WHERE Username = NEW.Username AND MachineType = NEW.MachineType); 
    UPDATE test SET Balance = Balance - cost WHERE Username = New.Username; 
END;; 
DELIMITER ; 

調查

CREATE TABLE test (
    ID int(10) unsigned NOT NULL AUTO_INCREMENT, 
    Username varchar(20) NOT NULL DEFAULT '', 
    Balance smallint(6) DEFAULT NULL, 
    PRIMARY KEY (ID) 
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8; 
DELIMITER ;; 
CREATE TRIGGER TRG2 AFTER UPDATE ON test FOR EACH ROW BEGIN 
    IF NEW.Balance > OLD.Balance THEN 
     INSERT INTO payments SET Username = NEW.Username, PaymentOn = NOW(), Amount = NEW.Balance - OLD.Balance; 
    END IF; 
END;; 
DELIMITER ; 

觸發器TRG1的問題在於,它不會從SELECT語句計算變量成本的值,並且始終將值0或任何在其聲明中設置爲DEFAULT的值。下一行的UPDATE查詢工作正常(無論值的代價從其聲明中獲取,或者分配了像SET cost = 100這樣的常量值)。 SELECT運行單獨給出所需的值成本

這段代碼有什麼問題?

在此先感謝。

+0

我試過'UPDATE驗船師SET餘額=餘額 - NEW.VehicleType其中username = New.Username;',但行不被更新。這意味着,我無法從INSERT行中獲取NEW.VehicleType。我真的做錯了什麼? – 2012-04-02 14:35:36

回答

1

您必須使用sintax SELECT場FROM表WHERE條件INTO變量

DROP TRIGGER TRG1 IF EXISTS; 
DELIMITER $$ 
CREATE TRIGGER TRG1 
AFTER INSERT ON investigation 
FOR EACH ROW BEGIN 
     DECLARE cst smallint; 
     SELECT Cost FROM inv_cost WHERE Username = NEW.Username AND MachineType = NEW.MachineType INTO cst; 
     UPDATE test SET Balance = Balance - cst WHERE Username = New.Username; 
END$$ 
DELIMITER ; 
+0

感謝您的回覆。但結果是一樣的。 – 2012-04-02 13:57:04

+0

這個查詢在mysql中返回什麼(用新值替換NEW.Username和NEW.MachineType)? - SELECT費用FROM inv_cost其中用戶名= NEW.Username AND MachineType = NEW.MachineType – 2012-04-02 14:01:25

+0

它返回一個數字值,我已經在inv_cost表中存儲了與用戶名和MachineType相對應的值。 – 2012-04-02 14:09:40