我经常使用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?
好吧,我知道,上面的一些问题可以通过编程测试来理解,但我也想知道这其中是否有依赖于数据库供应商的。
请照点光。
这是一个很好的问题,我昨天也有同样的问题。我考虑过这个问题,特别是搜索是否存在类似“ON UPDATE CASCADE”的东西,幸运的是SQL的设计师也考虑过这个问题。我同意泰德的观点。施特劳斯,我还评论了诺兰的案子。
When did I use it? Like Ted pointed out, when you are treating several databases at one time, and the modification in one of them, in one table, has any kind of reproduction in what Ted calls "satellite database", can't be kept with the very original ID, and for any reason you have to create a new one, in case you can't update the data on the old one (for example due to permissions, or in case you are searching for fastness in a case that is so ephemeral that doesn't deserve the absolute and utter respect for the total rules of normalization, simply because will be a very short-lived utility)
因此,我同意两点:
(a)是的,在很多时候,一个更好的设计可以避免这种情况;但
(b)在迁移、复制数据库或解决紧急情况的情况下,它是一个很好的工具,幸运的是,当我去搜索它是否存在时,它就在那里。
这是一个很好的问题,我昨天也有同样的问题。我考虑过这个问题,特别是搜索是否存在类似“ON UPDATE CASCADE”的东西,幸运的是SQL的设计师也考虑过这个问题。我同意泰德的观点。施特劳斯,我还评论了诺兰的案子。
When did I use it? Like Ted pointed out, when you are treating several databases at one time, and the modification in one of them, in one table, has any kind of reproduction in what Ted calls "satellite database", can't be kept with the very original ID, and for any reason you have to create a new one, in case you can't update the data on the old one (for example due to permissions, or in case you are searching for fastness in a case that is so ephemeral that doesn't deserve the absolute and utter respect for the total rules of normalization, simply because will be a very short-lived utility)
因此,我同意两点:
(a)是的,在很多时候,一个更好的设计可以避免这种情况;但
(b)在迁移、复制数据库或解决紧急情况的情况下,它是一个很好的工具,幸运的是,当我去搜索它是否存在时,它就在那里。