使用外键进行双边操作

Using foreign key to bilateral action

我的表使用外键:

Table一个

-----------------------------------------
id    |  name   |  type   | date
-----------------------------------------
1     |test.jpg |image/jpg| 2015-01-15
2     |test2.jpg|image/jpg| 2015-01-15
3     |test3.jpg|image/jpg| 2015-01-15

TableB

-----------------------------------------
id    |  title  | file_id | date
-----------------------------------------
1     |News 1   |1        | 2015-01-15
2     |News 2   |2        | 2015-01-15
3     |News 3   |3        | 2015-01-15

这是我的外键 Table B :

CONSTRAINT `news_ibfk_1` FOREIGN KEY (`file_id`) REFERENCES `Table A` (`id`) ON UPDATE NO ACTION

现在一切正常,我想知道如果我从 Table B 中删除一条记录,从 Table A 中删除 file_id 条记录,有什么办法吗?

所以我明白 "TableA.id" 是 "TableB.file_id" 的父级。

在这种情况下,您只能从 "TableA.id" 中删除没有子项的内容。 "TableB.file_id" 中的值也必须存在于 "TableA.id" 中。

你可以做的是在 "TableB" 上放置一个触发器,当删除完成时它会激活。然后您可以查看您删除的行中的值 "TableB.file_id" 是否仍在 "TableB.file_id" 中使用。如果不是这种情况,则删除您可以从 "TableA" 中删除它。

这里是关于触发器的 link:Triggers

我认为您需要使用 "after delete trigger"。 像这样:

CREATE OR REPLACE TRIGGER trName 
AFTER DELETE ON TableB

BEGIN 
    <look if any values from "TableA.id" are not used anymore in "TableB.file_id">
    <if that is the case, do a DELETE on that "TableA.id" line>
END;
/