为什么我会收到“外键不匹配”错误?

时间:2013-08-22 12:28:39

标签: sql sqlite

我不明白为什么会收到错误,你能解释一下吗?

sqlite> create table a (id text, val text);
sqlite> create table b (bid text, ref text, foreign key(ref) references a(text));
sqlite> insert into a values("1", "one");
sqlite> insert into b values("1", "one");
Error: foreign key mismatch

3 个答案:

答案 0 :(得分:4)

我觉得你在这里有一些奇怪的事情。我会写如下:

create table a (id text, val text, primary key(id));
create table b (bid text, ref text, foreign key (ref) references a(id));
insert into a values("1", "one");
insert into b values("one", "1");

在A上创建主键,然后从B引用它;不是我引用字段名而不是外键中的数据类型。

不匹配是因为您试图“匹配”one1。您应该切换B插入中的值。

SQL Fiddle

答案 1 :(得分:2)

表a ..

中没有名为text的字段

你可能打算这样做:

sqlite> create table a (id text, val text primary key(id));
sqlite> create table b (bid text, ref text, foreign key(ref) references a(val));
sqlite> insert into a values("1", "one");
sqlite> insert into b values("1", "one");

答案 2 :(得分:1)

您可能会收到此错误,因为您尚未在table a中声明主键。此外,在引用中您必须提及主键列名称而非数据类型。 例如

sqlite> create table a (id text PRIMARY KEY, val text);
                               // ^---Declared Primary key
sqlite> create table b (bid text, ref text, foreign key(ref) references a(text));
                                          refer primary key column--------^      
相关问题