[英]SQLite Delete row from Table A when columns are referenced as FOREIGN KEYS in other Tables B, C, etc
所以我有幾個表,但只會顯示 2 作為示例:
Table G
gNo | gName | gAddress
G1 | Jean | Bonalbo
G2 | Oscar | Berlin
G3 | Edd | Brisbane
G4 | Bob | California
Table B
gNo | gdate | rNo
G1 | 2019 | R21
G2 | 1993 | R03
G3 | 1989 | R26
G4 | 2020 | R04
現在,我需要從表 G 中刪除最后一行,但 SQLite 一直說存在 FOREIGN KEY 約束失敗。 這就是我所做的:
DELETE FROM G WHERE gNo = 'G4';
我知道這還不完整。 我嘗試在該行的末尾使用 CASCADE,但它引發了錯誤。 然后我嘗試使用DELETE FROM G JOIN Table B WHERE gNo = 'G4';
而且也沒有用。
我在這里很失落。
一些幫助?
您不能刪除由另一個表中的行引用的行 - 這是外鍵的功能之一。
您通常需要先刪除子記錄:
delete from b where gno = 'G4';
delete from g where gno = 'G4);
否則,您需要更改外鍵的定義,使其包含on delete cascade
選項:
create table b (
gno text references g(gno) on delete cascade,
gdate int,
rno text,
...
);
您需要使用cascade
定義外鍵約束。 您可以刪除現有約束並將外鍵定義為:
create table b (
. . .,
gno int references g(gno) on delete cascace
);
這告訴數據庫,當您刪除主表中的一行時,也要刪除引用。
這是一個 db<>fiddle。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.