2013-01-12 37 views
3

我試圖在SQLite中使用外鍵支持來維護具有自反連接的單表數據庫上的參照完整性。SQLite:使用自反連接刪除規則功能?

例如

PRAGMA foreign_keys = ON; 

create table tree (
    objectId text unique not null, 
    parentObjectID text, 
    foreign key (parentObjectID) references tree(parentObjectID) on delete cascade 
) 

我希望的行爲是當父行被刪除時,其子行和子行也被刪除。

然而,當我試圖刪除根行(其中預期的行爲將是數據庫中的所有其他行也被刪除),我得到這個錯誤:

sqlite> delete from tree where objectid = '0'; 
Error: foreign key mismatch 

是我的期望出用SQLite外鍵支持(和刪除行爲)可以提供?

回答

2

你的問題很簡單,你的FK parentObjectId引用parentObjectId而不是objectId並且SQLite在你嘗試使用這個表之前不會檢測到這一點混淆。如果您的FK的定義是這樣的:

foreign key (parentObjectID) references tree(objectID) on delete cascade 

fine manual

So, in other words, misconfigured foreign key constraints that require looking at both the child and parent are DML errors. The English language error message for foreign key DML errors is usually "foreign key mismatch" but can also be "no such table" if the parent table does not exist. Foreign key DML errors are may be reported if:

  • The parent table does not exist, or
  • The parent key columns named in the foreign key constraint do not exist, or
  • The parent key columns named in the foreign key constraint are not the primary key of the parent table and are not subject to a unique constraint using collating sequence specified in the CREATE TABLE, or
  • The child table references the primary key of the parent without specifying the primary key columns and the number of primary key columns in the parent do not match the number of child key columns.

第三點似乎適用於這裏,因爲parentObjectId既不是PK,也不限制是唯一的所以這就是爲什麼你不在嘗試修改表格內容(即使用DML語句而不是DDL語句)之前,不會看到錯誤。

+0

LOL ... Ouch。那麼,有第二套眼睛是很好的。我想知道要多久才能看到那個......嘆氣。謝謝! – xyzzycoder

+0

花了我一段時間才發現它,即使它藏在普通的網站。 –

+0

我看到了我現在預期的行爲。如果「根」行被刪除,則刪除規則級聯以產生空表。 – xyzzycoder