Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I construct a cross database query in MySQL?

Tags:

sql

mysql

I've got two databases on the same server. The Google gave me some hints but there wasn't anything "official" that I could find. Could someone point me to the documentation that explains how to do this? An explanation using PHP would be useful as well. Thanks!

like image 725
Avery Avatar asked Dec 29 '09 04:12

Avery


People also ask

What is cross-database query?

With cross-database queries, you can seamlessly query data from any database in the cluster, regardless of which database you are connected to. Cross-database queries can eliminate data copies and simplify your data organization to support multiple business groups on the same cluster.

How do I create a MySQL database query?

Open the MySQL Workbench as an administrator (Right-click, Run as Admin). Click on File>Create Schema to create the database schema. Enter a name for the schema and click Apply. In the Apply SQL Script to Database window, click Apply to run the SQL command that creates the schema.


2 Answers

I've got two databases on the same server. ...How do I construct a cross database query in MySQL?

You access other databases on the same MySQL instance by prefixing the table with the appropriate database name. IE:

SELECT *
  FROM this_database.table_1 t1
  JOIN that_database.table_2 t2 ON t2.column = t1.column

Keep in mind

A query executes with the credentials of the authentication used to set up the connection. If you want to query two tables simultaneously across two (or more) databases, the user used to run the query will need SELECT access to all databases involved.

Reference:

  • Identity Qualifiers
like image 115
OMG Ponies Avatar answered Oct 06 '22 19:10

OMG Ponies


SELECT * FROM DB1.myTable1 AS db1, DB2.myTable2 AS db2
like image 31
Tyler Smith Avatar answered Oct 06 '22 20:10

Tyler Smith