如何为postgres编写DELETE CASCADE?
技术问答
249 人阅读
|
0 人回复
|
2023-09-14
|
我正在手动为postgres构造DELETE CASCADE语句。
. m1 K* Q1 S4 _8 _7 C" `5 \: b( y5 w我有一个“交易”和一个“切片”表,如下所示:
( I+ G$ g1 @% |# B Table "public.slice"
* e$ G" Z& C# N4 s" M( E7 c9 n Column | Type | Modifiers 9 g% C5 {$ T" J& v# ~
----------+------+-----------) ^* N% \" [& d& j( m. `
id | text | not null2 X1 k$ k+ _2 x1 i
name | text |
; l3 E$ e; A) o+ s# YReferenced by:
6 p! F, N5 J4 g. f/ q% ? TABLE "transaction" CONSTRAINT "transaction_slice_id_fkey" FOREIGN KEY (slice_id) REFERENCES slice(id)/ O* l* n2 A& w; T- P
Table "public.transaction"
; K5 w1 v$ [$ E7 a# r6 _$ H Column | Type | Modifiers
' X; S1 K- ]& G( j----------+------+-----------' Q$ N* b3 ?# }8 F
id | text | not null& s/ z" z# ~3 d K1 n
slice_id | text | & l1 O% `5 L* F: `* h; `7 x
Referenced by:
. ?6 H$ o9 A! I6 O9 F/ v TABLE "classification_item" CONSTRAINT "classification_item_transaction_id_fkey" FOREIGN KEY (transaction_id) REFERENCES transaction(id)3 U( g8 T) }" |& h' Y$ b" M7 o
Table "public.classification_item"
$ X8 o( M' P' j$ ]! I Column | Type | Modifiers
1 N. c" z0 X; l----------------+------+-----------! Y# P$ G0 g+ F
id | text | not null2 q' O* g; @ j/ u
transaction_id | text | ! C W3 u+ }/ _
Foreign-key constraints:( p, }3 `/ d4 q; j" z( _. L1 C
"classification_item_transaction_id_fkey" FOREIGN KEY (transaction_id) REFERENCES transaction(id)
; S3 e: M" ~* X" \5 y9 f假设我要删除名称为“ my_slice”的切片所引用的所有事务和category_item。我需要写些什么?- r- P4 h- \9 l4 d$ C& V
=# delete from classification_item where transaction_id= #...?
# F0 u6 w: N' F( E" j0 g=# delete from transaction where slice_id= #...?
5 H% |, Q& m" a7 j: _* f=# delete from slice where name='my_slice';
$ J0 p" y; F2 s5 {, a" t7 P* A , |/ O* U) Y8 _! I
解决方案:/ M' O) T" {4 C
4 j. U# b: p7 d/ d9 v' k- t: c
) h" d0 Q% J% {- e! V7 }
7 B) y" {( E1 O( j8 V' @ t 万一您不能做别人建议的事情:) r& [. h6 F5 {
begin;
" b4 _3 R; C3 Y. E" G; A" N# ndelete from classification_item where transaction_id in (select id from "transaction" where slice_id = (select id from slice where name = 'my_slice'));; U+ G% w4 o* l4 ]2 p
delete from "transaction" where slice_id in (select id from slice where name='my_slice');& [3 R. P$ t |7 y
delete from slice where name='my_slice';
4 i: J. `0 A1 K' Y" x/ Tcommit; |
|
|
|
|
|