触发器无法处理约束

时间:2016-03-28 16:04:08

标签: mysql

我在accounting表上有一个触发器。当删除父enclosure行时,accounting中的所有子行都将被删除..

accountinginvoice删除的触发器 - 但如果enclosure中的父行被删除则无效?它仅在从accounting

中删除时有效

db结构

CREATE TABLE IF NOT EXISTS `enclosure` (
`id` mediumint(7) unsigned NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_danish_ci;

ALTER TABLE `enclosure`
 ADD PRIMARY KEY (`id`);

CREATE TABLE IF NOT EXISTS `accounting` (
`id` mediumint(7) unsigned NOT NULL,
  `enclosure_id` mediumint(7) unsigned NOT NULL,
  `invoice_id` mediumint(7) unsigned DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_danish_ci;

ALTER TABLE `accounting`
 ADD PRIMARY KEY (`id`), ADD KEY `enc_id` (`enclosure_id`), ADD KEY `invoice_id` (`invoice_id`);

DELIMITER //
CREATE TRIGGER `accounting_delete_invoice` AFTER DELETE ON `accounting`
 FOR EACH ROW BEGIN
    DELETE FROM `invoice` WHERE id=OLD.invoice_id;
END
//
DELIMITER ;

CREATE TABLE IF NOT EXISTS `invoice` (
`id` mediumint(7) unsigned NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_danish_ci;

ALTER TABLE `invoice`
 ADD PRIMARY KEY (`id`);

ALTER TABLE `accounting`
ADD CONSTRAINT `accounting_ibfk_12` FOREIGN KEY (`invoice_id`) REFERENCES `invoice` (`id`),
ADD CONSTRAINT `accounting_ibfk_17` FOREIGN KEY (`enclosure_id`) REFERENCES `enclosure` (`id`) ON DELETE CASCADE;

数据

INSERT INTO `enclosure` (`id`) VALUES ('1');
INSERT INTO `invoice` (`id`) VALUES ('1');
INSERT INTO `accounting` (`id`, `enclosure_id`, `invoice_id`) VALUES ('1', '1', '1');

的请求

DELETE FROM `enclosure` WHERE id=1; # row in `invoice` not deleted
DELETE FROM `accounting` WHERE id=1; # row in `invoice` deleted

0 个答案:

没有答案