如何在SQL中添加值时自动更新表

时间:2016-12-29 02:26:58

标签: mysql

我有一张桌子:

vacation_days

id    name     work_days      hire
-------------------------------------
 1    John        369       20151226
 2    Mike        767       20141123
 3    Josh       1166       20131020 

有一个招聘方式:

UPDATE vacation_days SET work_days = DATEDIFF(CURDATE(),DATE(hire))

但是如果我添加一个新行,我会得到空值:

id    name     work_days      hire
-------------------------------------
 1    John        369       20151226
 2    Mike        767       20141123
 3    Josh       1166       20131020 
 4    Richard    NULL       20120623

我试过像这样使用触发器:

CREATE TRIGGER onInsert BEFORE INSERT ON vacation_days
FOR EACH ROW
BEGIN
SET NEW.work_days = DATEDIFF(CURDATE(),DATE(hire))
END;

但是我收到错误:

 You have an error in your SQL syntax; check the manual that corresponds to 
 your MySQL server version for the right syntax to use near 
 ''vacation_days' FOR EACH ROW SET work_days = DATEDIFF(CURDATE(), DATE
 (NEW.hire))' at line 1

2 个答案:

答案 0 :(得分:0)

不要更新!只需使用视图:

create view v_vacation_days 
    select vd.*, DATEDIFF(CURDATE(), DATE(vd.hire)) as workdays
    from vacation_days vd;

每当您查询视图时,该值都将是最新的。

注意:您需要从表定义中删除workdays

答案 1 :(得分:0)

此处您正在使用Insert Before,但是在插入之前,Hire数据不可用,因此您无法获得计算的雇用日期。您想要指明NEWOLD租用数据。

使用以下“在触发前插入”作为用法,

DELIMITER //

CREATE TRIGGER vacation_days_before_insert
BEFORE INSERT
   ON vacation_days FOR EACH ROW
BEGIN
   -- Insert record into table
   INSERT INTO vacation_days 
   ( id,
     name,
     work_days,
     hire)
   VALUES
   ( NEW.id,
     NEW.name,
     DATEDIFF(CURDATE(),DATE(NEW.hire)),
     NEW.hire );

END; //

DELIMITER ;