簡體   English   中英

如何為postgres編寫DELETE CASCADE?

[英]How does one write a DELETE CASCADE for postgres?

我正在為postgres手動構建DELETE CASCADE語句。

我有一個'交易'和'切片'表,相關如下:

    Table "public.slice"
  Column  | Type | Modifiers 
----------+------+-----------
 id       | text | not null
 name     | text | 
Referenced by:
    TABLE "transaction" CONSTRAINT "transaction_slice_id_fkey" FOREIGN KEY (slice_id) REFERENCES slice(id)
 Table "public.transaction"
  Column  | Type | Modifiers 
----------+------+-----------
 id       | text | not null
 slice_id | text | 
Referenced by:
    TABLE "classification_item" CONSTRAINT "classification_item_transaction_id_fkey" FOREIGN KEY (transaction_id) REFERENCES transaction(id)
Table "public.classification_item"
     Column     | Type | Modifiers 
----------------+------+-----------
 id             | text | not null
 transaction_id | text | 
Foreign-key constraints:
    "classification_item_transaction_id_fkey" FOREIGN KEY (transaction_id) REFERENCES transaction(id)

假設我想要刪除名稱為“my_slice”的切片引用的所有事務和classification_items。 我需要寫什么?

=# delete from classification_item where transaction_id= #...? 
=# delete from transaction where slice_id= #...? 
=# delete from slice where name='my_slice';

Postgres外鍵支持CASCADE刪除:

slice_id integer REFERENCES slice(id) ON DELETE CASCADE

等等

萬一你不能做別人的建議:

begin;
delete from classification_item where transaction_id in (select id from "transaction" where slice_id = (select id from slice where name = 'my_slice'));
delete from "transaction" where slice_id in (select id from slice where name='my_slice');
delete from slice where name='my_slice';
commit;

它是在表中定義的soemthing而不是DELETE Query。 示例(查看order_id):

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)
);

您應該使用CASCADE刪除,即使您繼承了數據庫模式,也應該可以這樣做。 您只需修改約束以將CASCADE刪除添加到模式:

  1. 刪除並重新創建約束以添加CASCADE刪除:

     ALTER TABLE ONLY "transaction" DROP CONSTRAINT transaction_slice_id_fkey; ALTER TABLE ONLY "transaction" ADD CONSTRAINT transaction_slice_id_fkey FOREIGN KEY (slice_id) REFERENCES slice(id) ON DELETE CASCADE; ALTER TABLE ONLY "classification_item" DROP CONSTRAINT classification_item_transaction_id_fkey; ALTER TABLE ONLY "classification_item" ADD CONSTRAINT classification_item_transaction_id_fkey FOREIGN KEY (transaction_id) REFERENCES transaction(id) ON DELETE CASCADE; 
  2. 現在,以下查詢不僅會從表slice刪除my_slice記錄,還會從表transactionclassification_item引用它的所有記錄:

     DELETE FROM slice WHERE name='my_slice'; 

即使原始模式由像SQLAlchemy這樣的對象關系映射器創建,該過程也會起作用。 但是,在這種情況下,每當架構更改或重新創建時,請務必重新應用該“補丁”。 只有當它不能自動實現時,它畢竟不是一個好主意......

可以通過設置約束屬性“On delete”= CASCADE將其委派給DBMS。 請看一個例子

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM