如果启用外键验证,则无法插入适合我的外键定义的正确值。我在这里缺少什么?
$ sqlite3 test.db
sqlite> CREATE TABLE a (id INTEGER NOT NULL, item TEXT NOT NULL);
sqlite> CREATE TABLE b (id INTEGER NOT NULL, item TEXT NOT NULL,
ref INTEGER REFERENCES a (id));
sqlite> INSERT INTO a VALUES (16, 'test');
sqlite> PRAGMA foreign_keys = 1;
sqlite> INSERT INTO b VALUES (16, 'test2', 16);
Error: foreign key mismatch - "b" referencing "a"
sqlite> SELECT * FROM a;
16|test
答案 0 :(得分:1)
我用Google搜索并找到了this answer to a previous question,引用了documentation:
通常,外键约束的父键是父表的主键。如果它们不是主键,则父键列必须共同受UNIQUE约束或具有UNIQUE索引。
当您向a.id
列添加UNIQUE约束时,示例有效:
$ sqlite3
sqlite> CREATE TABLE a (id INTEGER UNIQUE NOT NULL, item TEXT NOT NULL);
sqlite> CREATE TABLE b (id INTEGER NOT NULL, item TEXT NOT NULL,
...> ref INTEGER REFERENCES a(id));
sqlite> INSERT INTO a VALUES (16, 'test');
sqlite> INSERT INTO b VALUES (16, 'test2', 16);
sqlite> SELECT * FROM a;
16|test
sqlite> SELECT * FROM b;
16|test2|16