如何使用 PDO 跨两个数据库运行带有连接的查询 [英] How to run a query with a join accross two databases with PDO
问题描述
我有两个 PDO 对象代表两个数据库,pdo1 和 pdo2,声明如下:
I've got two PDO objects representing two databaes, pdo1 and pdo2, declared as per the following:
try {
$pdo1 = new PDO('mysql:host=localhost;dbname=database1', 'user', 'password');
$pdo1->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$pdo1->exec('SET NAMES "utf8"');
}
^ 我对 $pdo2 也做了同样的事情,它是第二个数据库.
^ And I've done the same for $pdo2 which is for the second database.
到目前为止,我访问数据库的方式如下:
The way I've been accessing the database so far has been like the following:
try {
$sql = 'SELECT * from table1';
$result = $pdo1->query($sql);
}
现在我想运行一个查询,其中两个表跨两个数据库连接.如何使用两个 pdo 对象执行此操作?这是我所拥有的,但我坚持如何做我放置星号的 $result 部分:
Now I want to run a query where two tables are joined across two databases. How can I do this with the two pdo objects? Here's what I've got, but I'm stuck on how to do the $result part where I've put asterixis:
try {
$sql = 'SELECT database1.table1.name FROM database1.table1 LEFT JOIN database2.table2
ON database1.table1.userid = database2.table2.userid';
$result = $pdo***->query($sql);
}
以前,它会引用 $pdo1 或 $pdo2,但是如何组合该部分以从组合的 pdo 对象中提取结果?
Previously, it would refer to either $pdo1 or $pdo2, but how do you combine that part to pull the result from combined pdo objects?
推荐答案
使用one连接,然后做一个类似
Use one connection, then do a query like
SELECT ... FROM db1.tbl1 JOIN db2.tbl2 ...
(您将需要访问两个数据库的权限.)
(You will need permissions to access both databases.)
这篇关于如何使用 PDO 跨两个数据库运行带有连接的查询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!