sqlalchemy foreign keys works only with primary key?

穿精又带淫゛_ 提交于 2019-12-11 14:47:33

问题


Tables and foreign keys are creating ok, but working not ok:

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

But if i make t1(uuid) primary key, all works as expected:

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");

Creating an index doing nothing:

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

回答1:


The documentation says:

Usually, the parent key of a foreign key constraint is the primary key of the parent table. If they are not the primary key, then the parent key columns must be collectively subject to a UNIQUE constraint or have a UNIQUE index.



来源:https://stackoverflow.com/questions/17106642/sqlalchemy-foreign-keys-works-only-with-primary-key

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!