我经常使用ON DELETE CASCADE,但我从不使用ON UPDATE CASCADE,因为我不确定在什么情况下它会有用。
为了便于讨论,让我们看一些代码。
CREATE TABLE parent (
id INT NOT NULL AUTO_INCREMENT,
PRIMARY KEY (id)
);
CREATE TABLE child (
id INT NOT NULL AUTO_INCREMENT, parent_id INT,
INDEX par_ind (parent_id),
FOREIGN KEY (parent_id)
REFERENCES parent(id)
ON DELETE CASCADE
);
对于ON DELETE CASCADE,如果删除带有id的父级,则child中的记录parent_id = parent。Id将被自动删除。这应该没有问题。
This means that ON UPDATE CASCADE will do the same thing when id of the parent is updated? If (1) is true, it means that there is no need to use ON UPDATE CASCADE if parent.id is not updatable (or will never be updated) like when it is AUTO_INCREMENT or always set to be TIMESTAMP. Is that right? If (2) is not true, in what other kind of situation should we use ON UPDATE CASCADE? What if I (for some reason) update the child.parent_id to be something not existing, will it then be automatically deleted?
好吧,我知道,上面的一些问题可以通过编程测试来理解,但我也想知道这其中是否有依赖于数据库供应商的。
请照点光。