php sql 将来自不同数据库的多个表连接在一起
我有 3 个数据库,现在我需要将每个数据库中的多个表连接到单个查询中.我该怎么做?
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?
这是我的连接:
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
}
我有 3 个不同的用户,每个数据库都有一个唯一的密码.一个数据库存储 facebook-apps 和其他 iframe 应用程序的应用程序数据.另一个保存所有网上商店数据,如产品、订单、客户等,而第三个保存网站结构和内容.
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.
现在;我想以某种方式在单个查询中 JOIN
将它们三个放在一起.
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?
推荐答案
您需要一个可以访问所有三个数据库的用户.
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
相关文章