例如,我有以下表格:
person person_address address
========== ================== ===========
pid (PK) pid (FK) aid (PK)
... aid (FK) ...
我已将pid
设为ON DELETE CASCADE
,将aid
设为ON DELETE NO ACTION
。如果address
被删除,目标是从person
删除相关记录。
我试过了触发器:
CREATE TRIGGER pa_delete
AFTER DELETE ON person_address
FOR EACH ROW
DELETE FROM address
WHERE person_address.address_id = address.address_id
但是当我删除person
记录时,address
记录仍然存在。我做错了什么?
修改
涉及的表格:
CREATE TABLE IF NOT EXISTS `chkdcrm`.`person` (
`person_id` INT(11) NOT NULL AUTO_INCREMENT,
`first_name` VARCHAR(45) NOT NULL,
`last_name` VARCHAR(45) NOT NULL,
`tel` VARCHAR(20) NULL,
`fax` VARCHAR(20) NULL,
`mobile` VARCHAR(20) NOT NULL UNIQUE,
`email` VARCHAR(150) NOT NULL UNIQUE,
PRIMARY KEY (`person_id`))
ENGINE = InnoDB;
CREATE TABLE IF NOT EXISTS `chkdcrm`.`address` (
`address_id` INT(11) NOT NULL AUTO_INCREMENT,
`type` ENUM('Invoice', 'Shipping', 'Site', 'Mailing') NOT NULL,
`street` VARCHAR(100) NOT NULL,
`city` VARCHAR(100) NOT NULL,
`state` VARCHAR(30) NOT NULL,
`zip` VARCHAR(10) NOT NULL,
`country` VARCHAR(40) NOT NULL,
PRIMARY KEY (`address_id`))
ENGINE = InnoDB;
CREATE TABLE IF NOT EXISTS `chkdcrm`.`person_address` (
`address_id` INT(11) NOT NULL,
`person_id` INT(11) NOT NULL,
PRIMARY KEY (`address_id`, `person_id`),
CONSTRAINT `fk_pa_address`
FOREIGN KEY (`address_id`)
REFERENCES `chkdcrm`.`address` (`address_id`)
ON DELETE NO ACTION,
CONSTRAINT `fk_pa_person`
FOREIGN KEY (`person_id`)
REFERENCES `chkdcrm`.`person` (`person_id`)
ON DELETE CASCADE)
ENGINE = InnoDB;