2013-08-22 39 views
0

我不明白爲什麼我收到錯誤,請你解釋一下嗎?爲什麼我會收到「外鍵不匹配」錯誤?

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 

回答

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

2

你沒有一個字段表稱爲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"); 
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--------^  
相關問題