Joining Tables from Different Databases in SQLite
When working with multiple SQLite databases, it becomes necessary to join tables across databases to access and combine data. While SQLite does not natively support direct joining of tables from different databases, there is a workaround using the ATTACH command.
Attaching Databases
The ATTACH command allows you to attach an external database file to the current connection. This enables you to access the tables and data from the attached database. To attach a database, use the following syntax:
ATTACH DATABASE 'path/to/db.sqlite' AS 'alias';
Replace 'path/to/db.sqlite' with the path to the database file you want to attach, and 'alias' with an alias used to refer to the attached database.
Example
Consider a scenario where you have two SQLite databases: 'database1.db' and 'database2.db'. To attach the second database:
ATTACH DATABASE 'database2.db' AS 'db2';
Joining Tables
After attaching the databases, you can join tables across databases as if they were in the same database. Use the following syntax:
SELECT * FROM db1.table1 AS T1 INNER JOIN db2.table2 AS T2 ON T1.column1 = T2.column2;
Here, 'db1.table1' and 'db2.table2' are tables from attached databases 'db1' and 'db2', respectively.
Querying Attached Databases
To verify the attached databases, use the .databases command:
.databases
This will list all the currently attached databases and their aliases.
Limitations
Note that the database names 'main' and 'temp' are reserved for the primary and temporary databases, respectively. Avoid using these names for attached databases to prevent conflicts.
The above is the detailed content of How Can I Join Tables Across Different SQLite Databases?. For more information, please follow other related articles on the PHP Chinese website!