從股票 ubuntu 發行版上的命令列。
$ sqlite3
SQLite version 3.31.1 2020-01-27 19:55:54
Enter ".help" for usage hints.
Connected to a transient in-memory database.
Use ".open FILENAME" to reopen on a persistent database.
sqlite> .open dumb.db
sqlite> create table a (aid integer primary key, name text);
sqlite> create table b (bid integer, aid integer, name text, foreign key(aid) references a(aid));
sqlite> insert into b values (1,1,'wtf');
sqlite> select * from b;
1|1|wtf
sqlite> select * from a;
sqlite>
在我看來,插入應該失敗,因為表 a 中沒有“1”(或任何 id,實際上)的 id 值。
我是否從根本上誤解了外鍵、sqlite 或兩者?
是的,我之前問過這個問題的 sqlite2被正確回答為“版本不足”
uj5u.com熱心網友回復:
看起來好像您還沒有打開外鍵支持。
在插入之前添加
pragma foreign_keys; /* optional */
pragma foreign_keys = on; /* turns foreign key support on (off by default) */
例如:-
drop table if exists b;
drop table if exists a;
pragma foreign_keys;
pragma foreign_keys = on;
create table a (aid integer primary key, name text);
create table b (bid integer, aid integer, name text, foreign key(aid) references a(aid));
insert into b values (1,1,'wtf');
select * from b;
select * from a;
drop table if exists b;
drop table if exists a;
結果是 :-
insert into b values (1,1,'wtf')
> FOREIGN KEY constraint failed
> Time: 0s
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/365403.html
標籤:sqlite
上一篇:將一個數除以百分之一
下一篇:SQLITE外鍵約束違反沒有錯誤
