mysql触发器添加或减去库存数量,当项目被雇用时减去1项目返回时添加1

时间:2014-10-09 17:08:37

标签: mysql

嗨我的mysql触发器语法有问题,我希望它更新我的new transaction_id上的copy_instock行,当电影被雇用从copy_instock中减去1时,然后更新电影返回时将1重新添加到copy_instock。或者我如何以与MySql不同的方式实现此目的。 我的桌子在下面,我的触发器不正确

CREATE TABLE IF NOT EXISTS `hires` (
`transaction_id` int(11) NOT NULL,
`movie_id` int(11) NOT NULL,
`customer_id` int(11) NOT NULL,
`hire_cost` double(4,2) NOT NULL DEFAULT '3.00',
`date_hired` date DEFAULT NULL,
`days_hire` int(11) NOT NULL DEFAULT '1',
`date_returned` date DEFAULT NULL,
`total_cost` double(4,2) DEFAULT NULL,
`copy_instock` int(3) NOT NULL
) ENGINE=InnoDB AUTO_INCREMENT=13 DEFAULT CHARSET=utf8;



CREATE TRIGGER update_instock AFTER INSERT ON hires
FOR EACH ROW
BEGIN
if (date_returned != NULL) {
UPDATE hires SET (NEW.copy_instock = OLD.copy_instock - 1)
}
Elseif (date_returned != date) {
UPDATE hires SET (NEW.copy_instock = OLD.copy_instock + 1)
END

2 个答案:

答案 0 :(得分:1)

您需要设置de delimiter

DELIMITER $$

CREATE TRIGGER update_instock AFTER INSERT ON hires
FOR EACH ROW
BEGIN
-- your code
END$$

DELIMITER ;

答案 1 :(得分:0)

代码中不应该有{}。正确的语法是:

IF ... THEN
    ...
ELSEIF ... THEN
    ...
END IF;

还有东西!= null会重新输出错误的值,它应该是:

something IS NLLL

something IS NOT NULL

Reference

我不知道,如果这是你试图实现的,但是它已经纠正了语法:

CREATE TRIGGER update_instock AFTER INSERT ON hires
FOR EACH ROW
BEGIN
    IF (date_returned IS NULL) THEN
        UPDATE hires SET NEW.copy_instock = OLD.copy_instock - 1;
    ELSEIF (date_returned IS NOT NULL) THEN
        UPDATE hires SET NEW.copy_instock = OLD.copy_instock + 1;
    END IF;
END