我有一个如下所述的表,并且使用BEFORE INSERT触发器将列的值更新为会话定义的变量。 INSERT集的modified_by_user和created_by_user列均为预期的1。但是,UPDATE不会像我预期的那样将modified_by_user更改为2,而是将其保留为1.如何使用BEFORE UPDATE ON来更新列值?我正在使用MySQL 5.5。感谢
SET @users_id=1;
INSERT INTO notes(notes,record_status_id,date_created) VALUES("hello","active",NOW());
//modified_by_user=1, created_by_user=1, notes="hello"
SET @users_id=2;
UPDATE notes SET notes="goodby" WHERE id=1;
//modified_by_user=1, created_by_user=1, notes="goodby"
CREATE TABLE IF NOT EXISTS `notes` (
`id` INT UNSIGNED NOT NULL AUTO_INCREMENT ,
`notes` TEXT NULL ,
`record_status_id` VARCHAR(8) NOT NULL ,
`date_created` DATETIME NOT NULL ,
`date_modified` TIMESTAMP NOT NULL ,
`modified_by_user` INT UNSIGNED NULL ,
`created_by_user` INT UNSIGNED NULL ,
PRIMARY KEY (`id`) ,
INDEX `fk_notes_users1_idx` (`modified_by_user` ASC) ,
INDEX `fk_notes_users2_idx` (`created_by_user` ASC) ,
INDEX `fk_notes_record_status1_idx` (`record_status_id` ASC) ,
CONSTRAINT `fk_notes_users10`
FOREIGN KEY (`modified_by_user` )
REFERENCES `users` (`id` )
ON DELETE NO ACTION
ON UPDATE NO ACTION,
CONSTRAINT `fk_notes_users20`
FOREIGN KEY (`created_by_user` )
REFERENCES `users` (`id` )
ON DELETE NO ACTION
ON UPDATE NO ACTION,
CONSTRAINT `fk_notes_record_status1`
FOREIGN KEY (`record_status_id` )
REFERENCES `record_status` (`id` )
ON DELETE NO ACTION
ON UPDATE NO ACTION)
ENGINE = InnoDB;
DELIMITER $$
CREATE TRIGGER tg_notes_ins BEFORE INSERT ON notes FOR EACH ROW
BEGIN
IF NEW.created_by_user IS NULL OR NEW.created_by_user = '' THEN
SET NEW.created_by_user = @users_id;
SET NEW.modified_by_user = @users_id;
END IF;
END$$
CREATE TRIGGER tg_notes_upd BEFORE UPDATE ON notes FOR EACH ROW
BEGIN
IF NEW.modified_by_user IS NULL OR NEW.modified_by_user = '' THEN
SET NEW.modified_by_user = @users_id;
END IF;
END$$
DELIMITER ;
答案 0 :(得分:1)
在UPDATE上,如果查询没有为给定列指定值,则NEW.column不像我原先预期的那样是NULL,但是如果它没有改变则是该列的值(即前一个OLD.column)值)