使用外键删除时从另一个表中删除

时间:2016-03-14 09:30:03

标签: mysql database innodb

当我尝试使用外键删除模式中的某些信息时,我遇到了问题。 这是我的表

CREATE TABLE tb_class (class_ID INT PRIMARY KEY);

CREATE TABLE tb_product (fingerprint VARCHAR(255) PRIMARY KEY);

CREATE TABLE tb_class_product (class_ID INT,
fingerprint VARCHAR(255),
PRIMARY KEY (class_ID, fingerprint),
UNIQUE INDEX tb_class_product_UNIQUE (fingerprint ASC),
FOREIGN KEY (class_ID) REFERENCES tb_class(class_ID)
    ON UPDATE CASCADE
    ON DELETE CASCADE,
FOREIGN KEY (fingerprint) REFERENCES tb_product(fingerprint)
    ON UPDATE CASCADE
    ON DELETE CASCADE);

当我删除 tb_class 中的 class_ID 时,我想要 tb_class_product 中的信息和指纹中的信息 tb_product 会自动删除。

我已尝试将以下触发器添加到 tb_class_product ,但没有成功

DELIMITER //
CREATE TRIGGER tb_class_product_after_delete
AFTER DELETE ON tb_class_product FOR EACH ROW
BEGIN
    DELETE FROM tb_product WHERE tb_product.fingerprint=old.fingerprint;
END; //
DELIMITER ;

-------- -------- EDIT 好。我发现级联外键仅在删除主键时删除外键,但在删除外键时不删除主键。

此外,我发现当删除级联外键时,触发器不会运行。

现在我找到了一个适合我的解决方案。

CREATE TABLE tb_class (class_ID INT PRIMARY KEY);

CREATE TABLE tb_product (fingerprint VARCHAR(255) PRIMARY KEY);

CREATE TABLE tb_class_product (class_ID INT,
fingerprint VARCHAR(255),
PRIMARY KEY (class_ID, fingerprint),
UNIQUE INDEX tb_class_product_UNIQUE (fingerprint ASC),
FOREIGN KEY (class_ID) REFERENCES tb_class(class_ID),
FOREIGN KEY (fingerprint) REFERENCES tb_product(fingerprint));

DELIMITER //
CREATE TRIGGER tb_class_product_before_delete
BEFORE DELETE ON tb_class_product FOR EACH ROW
BEGIN
    IF @deleting_from_product IS NULL THEN
        SET @deleting_from_class_product=1;
        DELETE FROM tb_product WHERE tb_product.fingerprint=old.fingerprint;
        SET @deleting_from_class_product=NULL;
    END IF;
END; //
DELIMITER ;

DELIMITER //
CREATE TRIGGER tb_class_before_delete
BEFORE DELETE tb_class FOR EACH ROW
BEGIN
    DELETE FROM tb_class_product WHERE tb_class_product.class_ID=old.class_ID;
END; //
DELIMITER ;

DELIMITER //
CREATE TRIGGER tb_product_before_delete
BEFORE DELETE tb_product FOR EACH ROW
BEGIN
    IF @deleting_from_class_product IS NULL THEN
        SET @deleting_from_product=1;
        DELETE FROM tb_class_product WHERE tb_class_product.fingerprint=old.fingerprint:
        SET @deleting_from_product=NULL;
    END IF;
END; //
DELIMITER ;

1 个答案:

答案 0 :(得分:0)

使用您描述的方式声明索引,应该从其他表中自动删除数据。 你能不能给你正在使用的mysql版本,并说出删除的效果是什么 - 它会抛出错误吗?