Sql 为什么会出现“外键不匹配”错误?

Sql 为什么会出现“外键不匹配”错误?,sql,sqlite,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: fo

我不明白为什么会出错,你能解释一下吗

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

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

我想你有一些事情有点奇怪。我将这样写:

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引用它;我引用的不是字段名,也不是外键中的数据类型

不匹配是因为您试图匹配1和1。您应该在B insert中切换值


您可能会遇到此错误,因为您尚未在表a中声明主键。此外,在引用中,您必须提及主键列名而不是数据类型。 e、 g

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--------^