0

表和外键创建正常,但工作不正常:

SQLite version 3.7.9 2011-11-01 00:52:41
sqlite> pragma foreign_keys=on;
sqlite> 
sqlite> CREATE TABLE t1(id int primary key, uuid varchar(36));
sqlite> CREATE TABLE t2(id int primary key, t1_uuid varchar(36), FOREIGN KEY (t1_uuid)    REFERENCES t1(uuid));
sqlite> 
sqlite> INSERT INTO t1(uuid) values ("uuid-1");
sqlite> INSERT INTO t2(t1_uuid) values ("uuid-1");
Error: foreign key mismatch

但是,如果我制作 t1(uuid) 主键,一切都按预期工作:

sqlite> pragma foreign_keys=off;
sqlite> DROP TABLE t1;
sqlite> DROP TABLE t2;
sqlite> pragma foreign_keys=on;
sqlite> CREATE TABLE t1(id int, uuid varchar(36) primary key);
sqlite> CREATE TABLE t2(id int primary key, t1_uuid varchar(36), FOREIGN KEY (t1_uuid) REFERENCES t1(uuid));
sqlite> INSERT INTO t1(uuid) values ("uuid-1");
sqlite> INSERT INTO t2(t1_uuid) values ("uuid-1");

创建一个不做任何事情的索引:

sqlite> pragma foreign_keys=on;
sqlite> CREATE TABLE t1(id int primary key, uuid varchar(36));
sqlite> CREATE INDEX uuindex ON t1(uuid);
sqlite> CREATE TABLE t2(id int primary key, t1_uuid varchar(36), FOREIGN KEY (t1_uuid) REFERENCES t1(uuid));
sqlite> INSERT INTO t1(uuid) values ("uuid-1");
sqlite> INSERT INTO t2(t1_uuid) values ("uuid-1");
Error: foreign key mismatch
4

1 回答 1

1

文档说:

通常,外键约束的父键是父表的主键。如果它们不是主键,则父键列必须共同受 UNIQUE 约束或具有 UNIQUE 索引。

于 2013-06-14T10:55:06.513 回答