php sql将来自不同数据库的多个表连接在一起

时间:2022-05-07 07:40:54

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?

我有3个数据库,现在需要将它们中的每个表连接到一个singel查询中。我该怎么做呢?

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.

我有3个不同的用户,每个数据库都有一个唯一的密码。一个数据库为facebook应用程序和其他iframe应用程序存储应用程序数据。另一个包含所有的webshop数据,如产品、订单、客户等,第三个包含站点结构和内容。

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?

当我写这个问题的时候;我的一个想法是让另一个“超级”用户访问所有三个数据库,然后做一个regoular多表查询?这是一个可以接受的解决方案吗?

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

如果需要,是否需要在查询中指定哪个数据库?

1 个解决方案

#1


5  

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

#1


5  

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