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

触发器触发的条件是表还是字段?
如下的数据库,如果我更新px表的isdel字段,会相应更新其他2表中的isdel字段
但我想知道,如果我UPDATE 语句中,没有涉及到isdel字段的话,他也会触发这个触发器吗?
如下语句
SQL code

/* 这句肯定会触发触发器 */
UPDATE `px` SET `isdel` = 1 WHERE `id` = 1;

/* 下面这句呢?也会触发触发器? */
UPDATE `px` SET `desc` = "XXOO" WHERE `id` = 2;


如果上面第二条语句也会触发触发器,那该怎么改它才会在只有UPDATE中指明更新isdel字段才会触发触发器呢?

SQL code
 
/* 建表语句 */
DROP DATABASE IF EXISTS `testtest`;
CREATE DATABASE `testtest` DEFAULT CHARACTER SET utf8 COLLATE utf8_general_ci;
USE `testtest`;

DROP TABLE IF EXISTS `px`;
CREATE TABLE IF NOT EXISTS `px` (
  `id` int(2) NOT NULL AUTO_INCREMENT,
  `desc` varchar(10) CHARACTER SET gbk DEFAULT NULL,
  `isdel` bit(1) NOT NULL DEFAULT b'0' COMMENT '是否删除(0:不删除|1:删除)',
  PRIMARY KEY (`id`)
) ENGINE=InnoDB  DEFAULT CHARSET=utf8 AUTO_INCREMENT=1;

DROP TABLE IF EXISTS `spec`;
CREATE TABLE IF NOT EXISTS `spec` (
  `id` int(2) NOT NULL AUTO_INCREMENT,
  `pid` int(2) NOT NULL,
  `isdel` bit(1) NOT NULL DEFAULT b'0' COMMENT '是否删除(0:不删除|1:删除)',
  PRIMARY KEY (`id`),
  KEY `pact_id` (`pid`)
) ENGINE=InnoDB  DEFAULT CHARSET=utf8 AUTO_INCREMENT=1;

DROP TABLE IF EXISTS `goods`;
CREATE TABLE IF NOT EXISTS `goods` (
  `id` int(4) NOT NULL AUTO_INCREMENT,
  `pid` int(2) NOT NULL,
  `sid` int(2) NOT NULL,
  `isdel` bit(1) NOT NULL DEFAULT b'0' COMMENT '是否删除(0:不删除|1:删除)',
  PRIMARY KEY (`id`),
  KEY `pid` (`pid`),
  KEY `sid` (`sid`)
) ENGINE=InnoDB  DEFAULT CHARSET=utf8 AUTO_INCREMENT=1;

/* 添加约束 */
ALTER TABLE `goods`
  ADD CONSTRAINT `goods_ibfk_1` FOREIGN KEY (`pid`) REFERENCES `px` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
  ADD CONSTRAINT `goods_ibfk_2` FOREIGN KEY (`sid`) REFERENCES `spec` (`id`) ON DELETE CASCADE ON UPDATE CASCADE;

ALTER TABLE `spec`
  ADD CONSTRAINT `spec_ibfk_1` FOREIGN KEY (`pid`) REFERENCES `px` (`id`) ON DELETE CASCADE ON UPDATE CASCADE;
COMMIT;

/* 插入数据 */
INSERT INTO `px`(`isdel`) VALUES (0),(0),(0);
INSERT INTO `spec`(`pid`) VALUES (1),(1),(1),(2),(2),(3),(3);
INSERT INTO `goods`(`pid`,`sid`) VALUES (1,1),(1,2),(1,2),(1,3),(1,3),(1,3),(2,4),(2,5),(2,5),(2,5),(3,6),(3,7),(3,7),(3,7);

/* 添加触发器 */
/* 更新px的isdel字段时,更新spec和goods的isdel字段 */
DELIMITER $$
CREATE TRIGGER `hidden_px` BEFORE UPDATE ON `px`
FOR EACH ROW
BEGIN
UPDATE `spec`,`goods`
SET `spec`.`isdel` = NEW.`isdel`,`goods`.`isdel` = NEW.`isdel`
WHERE NEW.`id` = `spec`.`pid` AND NEW.`id` = `goods`.`pid`;
END$$
DELIMITER ;
COMMIT;


------解决方案--------------------
但我想知道,如果我UPDATE 语句中,没有涉及到isdel字段的话,他也会触发这个触发器吗?


但添加了IF判断,所以应该只是触发触发器,但是没进行相应更新吧?