我在accounting
表上有一个触发器。当删除父enclosure
行时,accounting
中的所有子行都将被删除..
accounting
从invoice
删除的触发器 - 但如果enclosure
中的父行被删除则无效?它仅在从accounting
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