SQLite - Joining 3 different databases at a single one

Viewed 79

I'm trying to Join tables from 3 different databases (A, B and C) which have columns in commom, but i got some issues. Each database has 1 table with the same name of the database.

First, I tried to do that using VSCode (sqlite3 extension) by attaching the databases B to A:

ATTACH 'A.db' AS db1;
ATTACH 'B.db' AS db2;

SELECT * FROM db1.A
INNER JOIN db2.B ON B.ColumnInCommon = A.ColumnInCommon;

I got the following error:

No such table: db1.A

Could anyone help me with another solution?

1 Answers

I believe that you have to believe what the message says. The following demonstrates that what you are doing does work:-

sqlite> .open 'C.db'
sqlite> ATTACH 'A.db' AS db1;
sqlite> ATTACH 'B.db' AS db2;
sqlite> PRAGMA database_list;
0|main|C:\Users\Mike\C.db
2|db1|C:\Users\Mike\A.db
3|db2|C:\Users\Mike\B.db
sqlite> CREATE TABLE IF NOT EXISTS main.C (ColumnInCommon);
sqlite> CREATE TABLE IF NOT EXISTS db1.A (ColumnInCommon);
sqlite> CREATE TABLE IF NOT EXISTS db2.B (ColumnInCommon);
sqlite> SELECT * FROM db1.A INNER JOIN db2.B ON B.ColumnInCommon = A.ColumnInCommon;
sqlite>

i.e. no error.

I can force an error using :-

sqlite> SELECT * FROM dbx.A INNER JOIN db2.B ON B.ColumnInCommon = A.ColumnInCommon;
Error: no such table: dbx.A
sqlite>

But this shouldn't apply as your ATTACH appears to have worked (pragma database_list; will confirm as used above). As such it is probably that the table itself does not exist. I'd suggest trying :-

 SELECT * FROM db1.sqlite_master;

This would then show the tables in the A(db1) database e.g. :-

sqlite> SELECT * FROM db1.sqlite_master;
table|A|A|2|CREATE TABLE A (ColumnInCommon)
sqlite>
Related