Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
886 views
in Technique[技术] by (71.8m points)

mysql - php sql join together multiple tables from different databases

I have 3 databases, and now I need to join several tables from each one of them into a singel query. How do I do this?

This is my connection:

try {
    $con_options = array(
        PDO::ATTR_EMULATE_PREPARES => false,
        PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
        PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8',
        PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,  // _SILENT (pub) || _WARNING || _EXCEPTION  (dev)
    );

    $con_1 = new PDO('mysql:host=localhost; dbname=database_1', 'user_1', 'pass_1', $con_options);
    $con_2 = new PDO('mysql:host=localhost; dbname=database_2', 'user_2', 'pass_2', $con_options);
    $con_3 = new PDO('mysql:host=localhost; dbname=database_3', 'user_3', 'pass_3', $con_options);

} catch (PDOException $err) { 
    //  catch, record/log and do stuff with errors
}

I have 3 different users with a unique password for each database. One database stores application-data for facebook-apps and other iframe applications. Another one holds all webshop data like products, orders, customers etc. while the third one holds site structure and content.

Now; I would like to JOIN the three of them together in a single query somehow.

While I was writing this question; One idea I got was to have another "super"-user with access to all three databases and just do a regoular multi table query? Would that be an acceptable solution?

If so, do I have to specify which database aswell in the query?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You will need a user that has access to all three databases.

You will JOIN them together by specifying full table name, something like this:

SELECT * FROM database_1.logs AS d1 LEFT JOIN database_2.users AS d2 
  ON d1.username = d2.username ORDER BY d1.timestamp DESC LIMIT 10

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...