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

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

问题描述:

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?

我有3个数据库,现在我需要将每个数据库中的几个表连接成一个singel查询。 我该怎么做? p>

这是我的连接: strong> p>

  try {
 $ con_options = 数组(
 PDO :: ATTR_EMULATE_PREPARES => false,
 PDO :: ATTR_DEFAULT_FETCH_MODE => PDO :: FETCH_ASSOC,
 PDO :: MYSQL_ATTR_INIT_COMMAND =>'SET NAMES utf8',
 PDO :: ATTR_ERRMODE =&gt  ; 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 =新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并做错误的事情\  n} 
  code>  pre> 
 
 

我有3个不同的用户,每个数据库都有一个唯一的密码。 一个数据库存储facebook-apps和其他iframe应用程序的应用程序数据。 另一个 一个拥有所有网络 商店数据,如产品,订单,客户等,而第三个数据包含网站结构和内容。 p>

现在; 我想以某种方式在一个查询中将 JOIN code>三个一起加入。 p>

我正在写这个问题; 我得到的一个想法是让另一个“超级”用户可以访问所有三个数据库并只进行一次多表查询? 这是否是一个可接受的解决方案? p>

如果是这样,我是否必须在查询中指定哪个数据库? p> div>

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