【问题标题】:Foreign key in main database referencing attached database主数据库中的外键引用附加数据库
【发布时间】:2014-04-12 22:42:57
【问题描述】:

SQLite3 中有什么方法可以在主数据库中使用外键来引用附加数据库中的列(反之亦然?)

我希望在多个进程之间共享附加的(只读)数据库,每个进程都有自己的(读/写)主数据库。

我这样创建父表(在数据库'ParentDB'中):

create table Parent (id integer primary key);

现在我在主数据库中试试这个:

attach 'parent.sqlite3' as ParentDB;
create table Child (id integer not null references Parent (id),
                    constraint PK_Child primary key (id));
insert into ParentDB.Parent (id) values (42);

当我尝试它时,它会创建没有错误的外键。现在我尝试在子表中插入一行:

insert into Child (id) values (42);

我得到这个错误:

Error: no such table: main.Parent

所以它似乎总是假设父表和子表属于同一个数据库。

还有外键语法does not allow you to specify which database the parent table belongs to

有解决办法吗?


This question 是相关的,但这里父表和子表都在同一个附加数据库中,而我将它们放在不同的数据库中。

【问题讨论】:

    标签: sqlite foreign-keys


    【解决方案1】:

    SQLite 的内置外键约束不适用于数据库。

    唯一的解决方法是手动编写执行相同检查的检查约束和触发器。

    【讨论】:

    • 根据 SQLite 文档,触发器只能作用于与被更改的表位于同一数据库中的表。请参阅此处标题为“触发器中 UPDATE、DELETE 和 INSERT 语句的语法限制”的部分:sqlite.org/lang_createtrigger.html
    猜你喜欢
    • 2018-08-14
    • 2020-09-17
    • 2015-12-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-06-05
    • 2013-02-23
    • 1970-01-01
    相关资源
    最近更新 更多