Mysql

如何在記錄更新或插入另一個表時創建觸發器以更新時間戳

  • December 21, 2016

我有一個表 t_task 和一個表 t_taskaction 與 t_task 的外鍵。我想從 t_task 更新時間戳,它在每次更新時都引用外鍵表單 t_taskaction 。

它在 t_task 表中沒有任何更新,而且我沒有收到任何錯誤。

USE `myTask`;
DELIMITER $$
CREATE TRIGGER `t_taskaction_AUPD` AFTER UPDATE ON `t_taskaction` FOR EACH ROW
BEGIN
   DECLARE idTask INT(11);
   DECLARE idTaskState INT(11);

   set @idTask = NEW.idTask;

   set @idTask = (SELECT idTaskState 
   FROM t_task WHERE idTask = @idTask);

   UPDATE t_task 
   SET idTaskState = @idTaskState
   WHERE idTask = @idTask;
END$$
DELIMITER ;

CREATE TABLE IF NOT EXISTS `myTask`.`t_task` (
 `idTask` INT(11) UNSIGNED NOT NULL AUTO_INCREMENT,
 `task` VARCHAR(100) NOT NULL,
 `idTaskState' INT(11) UNSIGNED NOT NULL DEFAULT 1,
 `description` LONGTEXT NOT NULL,
 `timestamp` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
 PRIMARY KEY (`idTask`)
)

CREATE TABLE IF NOT EXISTS `myTask`.`t_taskAction` (
 `idTaskAction` INT(11) UNSIGNED NOT NULL AUTO_INCREMENT,
 `idTask` INT(11) NOT NULL,
 `fecha` DATETIME NOT NULL,
 `action` VARCHAR(45) NOT NULL,
 `timestamp` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
 PRIMARY KEY (`idTaskAction`, `idTask`),
 CONSTRAINT `t_ifocTareaAccion2t_ifocTarea`
   FOREIGN KEY (`idTaskAction`)
   REFERENCES `myTask`.`t_task` (`idTask`)
   ON DELETE CASCADE
   ON UPDATE CASCADE)

CREATE TABLE IF NOT EXISTS `myTask`.`a_taskState` (
 `idTaskState` INT(11) UNSIGNED NOT NULL AUTO_INCREMENT,
 `order` INT(11) NULL DEFAULT NULL,
 `state` VARCHAR(45) NOT NULL,
 `timestamp` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
 PRIMARY KEY (`idTaskState`))

感謝邁克爾的幫助!

很高興知道 @variables 是使用者變數,沒有 @ 是局部變數。

以下剪輯效果很好

USE `myTask`;
DELIMITER $$
CREATE DEFINER=`root`@`localhost` TRIGGER `t_taskaction_AUPD` 
AFTER UPDATE ON `t_taskaction` 
FOR EACH ROW
BEGIN
   DECLARE _idTask INT(11);
   DECLARE _idTaskState INT(11);

   set _idTask = NEW.idTask;

   set _idTask = (SELECT idTaskState 
   FROM t_task WHERE idTask = _idTask);

   UPDATE t_task 
   SET timestamp = now()
   WHERE idTask = _idTask;
END$$
DELIMITER ;

引用自:https://dba.stackexchange.com/questions/58385