2013-04-30 53 views
4

根據this空外鍵是被允許的,除非並且直到我們向模式添加適當的「NOT NULL」約束。當PRAGMA foreign_keys = ON時,它允許在sqlite中有空外鍵嗎?

,但我看到了一些不同的行爲,

sqlite> PRAGMA Foreign_keys; 
1 
sqlite> create table proc (pid integer, name text, ppid integer, foreign key (ppid) 
references proc (id)); 
sqlite> .schema proc 
CREATE TABLE proc (pid integer, name text, ppid integer, foreign key (ppid) references 
proc (id)); 

sqlite> insert into proc (pid, name, ppid) values (0, "init", null); 
Error: foreign key mismatch 

sqlite> PRAGMA Foreign_keys=OFF; 
sqlite> PRAGMA Foreign_keys; 
0 

sqlite> insert into proc (pid, name, ppid) values (0, "init", null) 
sqlite> select * from proc; 
0|init| 

我怎麼能允許sqlite的空外鍵時PRAGMA foreign_keys = ON?或者根本不可能?

+0

這裏'外鍵(PPID)引用PROC(ID)'是一個錯字,應該是'外鍵(PPID)引用proc(pid)',並按@CL建議。我讓'pid'成爲'PRIMARY KEY'。這是工作在sqlite提示符,但不是在android-sqlite中。 android is throwing exception android.database.sqlite.SQLiteConstraintException:外鍵約束失敗(代碼19)' – Rupesh 2013-04-30 18:26:44

+0

嗨Rupesh,我得到外鍵爲空。你可以看看它。這些是我的2表。表1 - 最終字符串DATABASE_CREATE_TABLE =「如果不存在,創建表scannerValuess(id整數,partName文本null,成本文本null,外鍵(id)引用scannerUserValuess(userid))」 ;表2 - 最終字符串DATABASE_CREATE_TABLE_USER =「如果不存在,創建表scannerUserValuess(userid整數主鍵自動增量,名稱文本非空,移動文本非空,地址文本非空,日期文本非空)」;請儘快幫我。提前感謝。 – Naveen 2016-11-01 11:41:56

回答

1
  1. ID列被命名爲pid,不id
  2. 父鍵列必須具有UNIQUEPRIMARY KEY約束。
+0

'ID'是一個錯字..是的,當我做了一個PRIDARY KEY,它的工作就像魅力..謝謝。 – Rupesh 2013-04-30 17:41:32

+0

,但這不是在android-sqlite中工作.. :( – Rupesh 2013-04-30 18:22:30

+2

我正在使用[ContentValues](http://developer.android.com/reference/android/content/ContentValues.html)在表中插入記錄,插入值null應該使用API​​ [putNull()](http://developer.android.com/reference/android/content/ContentValues.html#putNull(java.lang.String))。 – Rupesh 2013-04-30 18:54:54

0

嘗試通過改變你的表創建語句添加foreign key clause

CREATE TABLE proc (pid integer, name text, ppid integer, foreign key (ppid) references 
proc (id) ON UPDATE CASCADE ON DELETE SET NULL);