日期:2014-05-16  浏览次数:20800 次

如何实现如下效果?
我需要在插入一条记录的时候同时更新相关记录,但是如下的trigger会报错,因为mysql不允许在trigger中update,如何能实现相同的效果?
SQL code
DELIMITER $$
DROP TRIGGER /*!50032 IF EXISTS */ `tbl_afterinsert_trigger`$$

CREATE
    TRIGGER `tbl_afterinsert_trigger` AFTER INSERT ON `tbl` 
FOR EACH ROW BEGIN
    IF NEW.group_id > 0 THEN
        SET @cnt = (SELECT count(*) FROM tbl WHERE is_show = 1 AND group_id = NEW.group_id AND toprank_id = NEW.toprank_id AND time_windows = NEW.time_windows);
        IF @cnt > 1 THEN
            SELECT id INTO @id FROM tbl WHERE is_show = 1 AND group_id = NEW.group_id AND toprank_id = NEW.toprank_id AND time_windows = NEW.time_windows ORDER BY created_at DESC LIMIT 1;
            UPDATE tbl SET is_show = 0 WHERE group_id = NEW.group_id AND toprank_id = NEW.toprank_id AND time_windows = NEW.time_windows AND id <> @id;
        END IF;
    END IF;
END;
$$
DELIMITER ;


------解决方案--------------------
在TRIGGER中无法实现,MYSQL不允许在TRIGGER中对本表操作
------解决方案--------------------
trigger实现不了此操作的。
------解决方案--------------------
这个没有办法,你只能在你自己的程序中实现了。 MYSQL中在表的触发器中无法对自身表进行操作以免形成递归触发。