当 PRAGMA foreign_keys=ON 时,是否允许在 sqlite 中有空外键?

Rup*_*esh 6 sqlite android-sqlite

根据这个空外键是允许的,除非并且直到我们向模式添加适当的“NOT NULL”约束。

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

sqlite> PRAGMA Foreign_keys;
1
sqlite> create table proc (
sqlite>   pid integer,
sqlite>   name text,
sqlite>   ppid integer,
sqlite>   foreign key (ppid) references proc (id)
sqlite> );
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)
sqlite> 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)
sqlite> values (0, "init", null);
sqlite> select * from proc;
0|init|
Run Code Online (Sandbox Code Playgroud)

当 PRAGMA foreign_keys=ON 时,如何在 sqlite 中允许空外键?或者根本不可能?

CL.*_*CL. 1

  1. ID 列被命名为pid,而不是id
  2. 父键列必须具有UNIQUEorPRIMARY KEY约束。

  • 我正在使用 [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))。 (2认同)