SQLite - 如何连接来自不同数据库的表?
我有一个使用 SQLite 数据库的应用程序,并且一切正常.我现在正在添加需要第二个 SQLite 数据库的新功能,但我很难弄清楚如何连接来自不同数据库的表.
I have an application that uses a SQLite database and everything works the way it should. I'm now in the process of adding new functionalities that require a second SQLite database, but I'm having a hard time figuring out how to join tables from the different databases.
如果有人能帮我解决这个问题,我将不胜感激!
If someone can help me out with this one, I'd really appreciate it!
见这个问题 例如,当您附加已接受的答案中提到的数据库时,您可以适应您的语言.
See this question for an example case you can adapt to your language when you attach databases as mentioned in the accepted answer.
推荐答案
如果 ATTACH 是 在您的 Sqlite 构建中激活(它应该在大多数构建中),您可以使用 ATTACH 关键字将另一个数据库文件附加到当前连接.可以附加的 db 数量限制 是编译时设置(SQLITE_MAX_ATTACHED),当前默认为 10,但这也可能因您的构建而异.全局限制为 125.
If ATTACH is activated in your build of Sqlite (it should be in most builds), you can attach another database file to the current connection using the ATTACH keyword. The limit on the number of db's that can be attached is a compile time setting(SQLITE_MAX_ATTACHED), currently defaults to 10, but this too may vary by the build you have. The global limit is 125.
attach 'database1.db' as db1;
attach 'database2.db' as db2;
您可以看到所有连接的数据库与关键字
You can see all connected databases with keyword
.databases
那么您应该可以执行以下操作.
Then you should be able to do the following.
select
*
from
db1.SomeTable a
inner join
db2.SomeTable b on b.SomeColumn = a.SomeColumn;
注意[t]数据库名称main
和temp
是为主数据库和数据库保留的,用于保存临时表和其他临时数据对象.这两个每个数据库连接都存在数据库名称,不应将其用于附件".
Note that "[t]he database names main
and temp
are reserved for the primary database and database to hold temporary tables and other temporary data objects. Both of these database names exist for every database connection and should not be used for attachment".
相关文章