主数据库中的外键引用附加的数据库 [英] Foreign key in main database referencing attached database

查看:162
本文介绍了主数据库中的外键引用附加的数据库的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在SQLite3中,有什么办法在主数据库中有一个引用附加数据库中的列的外键(反之亦然?)

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

我创建父表在数据库'ParentDB'):

  create table Parent(id integer primary key); 

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

 附加'parent.sqlite3'作为ParentDB; 
create table Child(id integer not null引用父(id),
约束PK_Child主键(id));
插入到ParentDB.Parent(id)值(42);

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

  insert into Child(id)values(42); 

我得到这个错误:

  Error:no such table:main.Parent 

它始终假定父表和子表属于同一个数据库。



另外,外键语法不允许您指定父表所属的数据库



是否有解决方法?






这个问题是相关的,但是在这里两个父表和子表在相同的附加数据库中,而我将它们放在单独的数据库中。

解决方案

SQLite内置的外部关键约束不能跨数据库工作。

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


Is there any way in SQLite3 to have a foreign key in the main database that references columns in an attached database (or vice-versa?)

I hope to share the attached (read-only) database between multiple processes, each of which has its own (read/write) main database.

I create the parent table like this (in database 'ParentDB'):

create table Parent (id integer primary key);

Now I try this in the main database:

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

When I try it it creates the foreign key with no errors. Now I try to insert a row into the child table:

insert into Child (id) values (42);

And I get this error:

Error: no such table: main.Parent

So it seems it always assumes the parent and child tables belong to the same database.

Also the foreign key syntax does not allow you to specify which database the parent table belongs to.

Is there a workaround?


This question is related, but here both the parent and child tables are in the same attached database, whereas I have them in separate databases.

解决方案

SQLite's built-in foreign key constraints do not work across databases.

The only workaround would be to manually write check constraints and triggers that do the same checking.

这篇关于主数据库中的外键引用附加的数据库的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆