Bhavesh Gangani Bhavesh Gangani - 6 months ago 9
PHP Question

Select multiple tables from different databases

how to use two tables in a single query, which are in different databases, means,

SELECT table1.id, table1.name, table2.id, table2.telephone
FROM table1, table2
WHERE table1.id = table2.id


here,
table1
and
table2
are in separate database.

Answer

You can do cross-database joins, no problem. Simply prefix your table name with database name.

SELECT t1.id, t1.name, t2.id, t2.telephone
FROM db1.table1 t1
INNER JOIN db2.table2 t2 on t1.id = t2.id;

Be wary of permissions, though. If a user doesn't have access to one of the databases, this select will fail.