gpt4 book ai didi

sql - Postgres 外键 'on update' 和 'on delete' 选项如何工作?

转载 作者:行者123 更新时间:2023-11-29 11:08:58 26 4
gpt4 key购买 nike

谁能清楚地解释/举例说明这些函数的作用,以及何时适合使用它们?

最佳答案

直接来自 the manual ...

We know that the foreign keys disallow creation of orders that do not relate to any products. But what if a product is removed after an order is created that references it? SQL allows you to handle that as well. Intuitively, we have a few options:

Disallow deleting a referenced product

Delete the orders as well

Something else?

CREATE TABLE order_items (
product_no integer REFERENCES products ON DELETE RESTRICT,
order_id integer REFERENCES orders ON DELETE CASCADE,
quantity integer,
PRIMARY KEY (product_no, order_id)
);

Restricting and cascading deletes are the two most common options. RESTRICT prevents deletion of a referenced row. NO ACTION means that if any referencing rows still exist when the constraint is checked, an error is raised; this is the default behavior if you do not specify anything. (The essential difference between these two choices is that NO ACTION allows the check to be deferred until later in the transaction, whereas RESTRICT does not.) CASCADE specifies that when a referenced row is deleted, row(s) referencing it should be automatically deleted as well. There are two other options: SET NULL and SET DEFAULT. These cause the referencing columns to be set to nulls or default values, respectively, when the referenced row is deleted. Note that these do not excuse you from observing any constraints. For example, if an action specifies SET DEFAULT but the default value would not satisfy the foreign key, the operation will fail.

Analogous to ON DELETE there is also ON UPDATE which is invoked when a referenced column is changed (updated). The possible actions are the same.

编辑:您可能想看看这个相关问题:When/Why to use Cascading in SQL Server? .问题/答案背后的概念是相同的。

关于sql - Postgres 外键 'on update' 和 'on delete' 选项如何工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/225881/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com