2

一個外鍵關係有兩個表如何添加SQLite中

create table A(
    id integer primary key autoincrement, 
    subject text not null, 
); 

create table B(
    id integer primary key autoincrement, 
    text integer references A(id) 
     on delete restrict 
     deferrable initially deferred 
     unique 
); 

B錶行,應掛A。 所以,我和一個外鍵AB.text ..

我加入一些隨機數據與PK值1和表A 現在2,我試圖創建一個text值參照5乙的表格數據是不存在的,但它仍然可以存儲..

爲什麼這是工作和如何解決它?

回答

3

您必須啓用外鍵支持:

PRAGMA foreign_keys=ON; 

參考:http://www.sqlite.org/foreignkeys.html

例子:

sqlite> create table A(
    ...>  id integer primary key autoincrement, 
    ...>  subject text not null 
    ...>); 
sqlite> 
sqlite> create table B(
    ...>  id integer primary key autoincrement, 
    ...>  text integer references A(id) 
    ...>   on delete restrict 
    ...>   deferrable initially deferred 
    ...>   unique 
    ...>); 
sqlite> insert into a values(1,1),(2,2); 
sqlite> insert into b(text) values(3); 
sqlite> pragma foreign_keys=on; 
sqlite> insert into b(text) values(4); 
Error: foreign key constraint failed 
sqlite> 
相關問題