问题
I am writing a trigger to UPDATE a row in a table AFTER INSERT on another table. Here are the scripts of the tables:
Table 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),
)
Table investigation
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 ;
Table investigator
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 ;
The problem with trigger TRG1 is that it does not compute the value of the variable cost from the SELECT statement, and always takes the value 0 or whatever is set to DEFAULT in its declaration. The UPDATE query on the next line works good (with whatever value cost takes from its declaration OR if it is assigned a const value like SET cost = 100
;). The SELECT run separately gives the required value of Cost.
What is wrong with this code?
Thanks in advance.
回答1:
You have to use the sintax SELECT field FROM table WHERE condition INTO variable
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 ;
来源:https://stackoverflow.com/questions/9977690/cannot-fetch-a-value-from-a-select-query-inside-a-trigger