当其他字段更新时,mysql触发更新字段

时间:2013-11-22 13:21:40

标签: mysql

我有一个mysql表,它以非常简单的结构存储我的客户:

CREATE TABLE IF NOT EXISTS `recipients` (
  `recipient_id` int(8) unsigned NOT NULL AUTO_INCREMENT,
  `first_name` varchar(50) COLLATE utf8mb4_unicode_ci NOT NULL,
  `last_name` varchar(50) COLLATE utf8mb4_unicode_ci NOT NULL,
  `email` varchar(150) COLLATE utf8mb4_unicode_ci NOT NULL,
  `address` varchar(150) COLLATE utf8mb4_unicode_ci NOT NULL,
  `address2` varchar(150) COLLATE utf8mb4_unicode_ci NOT NULL,
  `city` varchar(85) COLLATE utf8mb4_unicode_ci NOT NULL,
  `postal` varchar(100) COLLATE utf8mb4_unicode_ci NOT NULL,
  `state` varchar(8) COLLATE utf8mb4_unicode_ci NOT NULL,
  `country` varchar(10) COLLATE utf8mb4_unicode_ci NOT NULL,
  `phone_1` varchar(30) COLLATE utf8mb4_unicode_ci NOT NULL,
  `phone_2` varchar(30) COLLATE utf8mb4_unicode_ci NOT NULL,
  `birth_date` date NOT NULL,
  `anniversary` date NOT NULL,
  PRIMARY KEY (`recipient_id`),
  KEY `email` (`email`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci AUTO_INCREMENT=1 ;

我正在寻找的是当国家/地区字段更改为某些特定文本时,使mysql将状态字段更新为0。即如果国家/地区更改为英国,我希望州字段可自动设置为“N / A”。

我知道我可以继续运行更新语句,但我想知道mysql是否可以这样做,所以我不必担心它。

1 个答案:

答案 0 :(得分:3)

您可以使用触发器,请参阅以下示例:

-- first you must change delimiter
DELIMITER $$

-- create the new trigger, if you want to update it then before create you must do
-- DROP TRIGGER IF EXISTS your_name_here
CREATE TRIGGER your_name_here BEFORE UPDATE ON recipients FOR EACH ROW
BEGIN
  -- check if country now is UK
  IF NEW.country = 'UK' THEN
    -- if so, do your work
    SET NEW.state = 'N/A';
  END IF;

  -- you can put more code here as needed!
END $$

-- then reset delimiter
DELIMITER ;

另见文档:http://dev.mysql.com/doc/refman/5.1/en/create-trigger.html