满足条件时删除触发器

时间:2015-04-12 16:36:48

标签: mysql triggers sql-delete

我知道这是一个简单的问题,但我无法在任何地方找到答案。

那是我的表:

city  | CREATE TABLE `city` (
  `ID` int(11) NOT NULL,
  `Name` char(35) NOT NULL DEFAULT '',
  `CountryCode` char(3) NOT NULL DEFAULT '',
  `District` char(20) NOT NULL DEFAULT '',
  `Population` int(11) NOT NULL DEFAULT '0',
  PRIMARY KEY (`ID`),
  KEY `FKcode99` (`CountryCode`),
  CONSTRAINT `FKcode99` FOREIGN KEY (`CountryCode`) REFERENCES `country` (`code`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 |

问题是:如果要删除某个城市,人口必须为275,000或更少。

我试过

ALTER TABLE `world`.`city` 
RENAME TO  `world`.`DeleteCity` ;
USE `world`;

DELIMITER $$

DROP TRIGGER IF EXISTS world.DeleteCity_ADEL$$
USE `world`$$


CREATE TRIGGER `DeleteCity_ADEL` AFTER DELETE ON `DeleteCity` FOR EACH ROW
IF (OLD.population <= 275000) THEN
    DELETE FROM city WHERE NEW.name=OLD.name;
END IF;
$$
DELIMITER ;

但它不起作用。有谁能够帮我?

1 个答案:

答案 0 :(得分:0)

我会这样做:

CREATE TRIGGER `DeleteCity_ADEL` BEFORE DELETE ON `DeleteCity` FOR EACH ROW
IF (OLD.population > 275000) THEN
     SIGNAL SQLSTATE '45123'
      SET MESSAGE_TEXT = 'If you want to delete a city, the population must be 275,000 or less.';
END IF;
/

当somone尝试删除包含&gt;的记录时,此触发器会引发错误。 275,000并向他返回一个明确的解释(错误信息) 如果人口少于或等于275,000,则会默默删除记录。