【问题标题】:SQLITE 3 foreign key constraint violated without error [duplicate]SQLITE 3外键约束违反没有错误[重复]
【发布时间】:2021-11-25 10:55:51
【问题描述】:

从股票 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 中没有 id 值“1”(或任何 id,实际上)。

我是从根本上误解了外键、sqlite 还是两者兼而有之?

是的,I previously asked this for sqlite2 被正确回答为“版本不足”

【问题讨论】:

    标签: sqlite


    【解决方案1】:

    您好像还没有打开Foreign key support

    插入前添加

    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
    

    【讨论】:

      猜你喜欢
      • 2020-02-15
      • 1970-01-01
      • 2011-10-17
      • 2012-03-03
      • 2018-08-26
      • 2021-10-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多