Mysql触发器或存储过程在同一个表中更新B列时更新A列

时间:2016-04-26 05:07:42

标签: mysql stored-procedures triggers

我创建了一个库数据库,其中一个表是transaction,如下所示

CREATE TABLE action
(
t_id int NOT NULL AUTO_INCREMENT,
b_id int,
m_id int,
borrow_timestamp TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
is_returned Bool Default 0,
is_lost Bool,
is_damaged Bool,
return_timestamp TIMESTAMP,
f_id int,
PRIMARY KEY (t_id),
CONSTRAINT fk_bookId FOREIGN KEY (b_id) REFERENCES book(b_id),
CONSTRAINT fk_memberId FOREIGN KEY (m_id) REFERENCES member(m_id),
CONSTRAINT fk_fineId FOREIGN KEY (f_id) REFERENCES fine(f_id)
);

我想将return_timestamp arrtibute更新为时间戳,即is_returned更改为1时的时间戳

我试过这个

CREATE TRIGGER update_return_timestamp
AFTER UPDATE
ON action FOR EACH ROW

BEGIN
DECLARE return_timestamp timestamp;

   SELECT is_returned FROM action
   IF is_return IS 1
        BEGIN
           INSERT INTO transaction (return_timestamp) VALUES (now())
        END
    COMMIT TRANSACTION
END

我哪里错了?或者什么是正确的方法?我不知道该怎么做

1 个答案:

答案 0 :(得分:1)

您可以在更新记录之前声明Trigger。 如果新更新设置为is_returned字段,则设置return_timestamp字段。

CREATE TRIGGER update_return_timestamp

BEFORE UPDATE ON `action` FOR EACH ROW
BEGIN

IF NEW.is_returned = 1 Then
    Set NEW.return_timestamp = CURRENT_TIMESTAMP
END IF;

END