2013-04-19 66 views
1

根據SQLite foreign key documentation,它應該是創建兩個數據庫的方式,並且如果更新父字段,那麼引用父字段的字段也會更新。SQLITE ON UPDATE操作

問題:當我按照下面步驟,一切工作正常,直到最後一個命令 SELECT * FROM track;因爲結果仍然一樣喜歡以下由此應該改變的結果,在在最後表示。

trackid trackname   trackartist 
    ------- ----------------- ----------- 
    11  That's Amore  1 
    12  Christmas Blues 1 
    13  My Way    2 

編碼:

-- Database schema 
CREATE TABLE artist(
    artistid INTEGER PRIMARY KEY, 
    artistname TEXT 
); 
CREATE TABLE track(
    trackid  INTEGER, 
    trackname TEXT, 
    trackartist INTEGER REFERENCES artist(artistid) ON UPDATE CASCADE 
); 

sqlite> SELECT * FROM artist; 
artistid artistname  
-------- ----------------- 
1   Dean Martin  
2   Frank Sinatra  

sqlite> SELECT * FROM track; 
trackid trackname   trackartist 
------- ----------------- ----------- 
11  That's Amore  1 
12  Christmas Blues 1 
13  My Way    2 

sqlite> -- Update the artistid column of the artist record for "Dean Martin". 
sqlite> -- Normally, this would raise a constraint, as it would orphan the two 
sqlite> -- dependent records in the track table. However, the ON UPDATE CASCADE clause 
sqlite> -- attached to the foreign key definition causes the update to "cascade" 
sqlite> -- to the child table, preventing the foreign key constraint violation. 
sqlite> UPDATE artist SET artistid = 100 WHERE artistname = 'Dean Martin'; 

sqlite> SELECT * FROM artist; 
artistid artistname  
-------- ----------------- 
2   Frank Sinatra  
100  Dean Martin  

sqlite> SELECT * FROM track; 
trackid trackname   trackartist 
------- ----------------- ----------- 
11  That's Amore  100 
12  Christmas Blues 100 
13  My Way    2 

這是爲什麼?

回答

1

你應該更加小心閱讀fine manual

2.啓用外鍵支持
[...]
假設庫啓用外鍵約束編譯,它仍然必須在運行時由應用程序啓用,使用PRAGMA foreign_keys命令。例如:

sqlite> PRAGMA foreign_keys = ON; 

外鍵約束默認(向後兼容)禁用,所以必須分別對每個數據庫連接單獨啓用。

所以,如果你這樣說:

sqlite> PRAGMA foreign_keys = ON; 
sqlite> UPDATE artist SET artistid = 100 WHERE artistname = 'Dean Martin'; 

然後你會看到在track,你期待100S。當然,這假設你的SQLite是用FK支持編譯的。