6

according to this null foreign keys are allowed unless and until we are adding the appropriate "NOT NULL" constraint to the schema.

but I am seeing the some different behavior,

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|

how can I allow null foreign key in sqlite when PRAGMA foreign_keys=ON? or it is not possible at all?

4

2 回答 2

0
  1. ID 列名为pid,而不是id
  2. 父键列必须具有UNIQUEorPRIMARY KEY约束。
于 2013-04-30T17:13:51.627 回答
-1

尝试通过将表创建语句更改为添加外键子句:

CREATE TABLE proc (pid integer, name text, ppid integer, foreign key (ppid) references 
proc (id) ON UPDATE CASCADE ON DELETE SET NULL);
于 2015-02-17T20:29:54.560 回答