2

I have two sql hosts on which I want to run my sql query. It should look something like this: Assuming two hosts -> host1.DB1 & host2.DB2

select a.*, b.* from host1.DB1.table as a join host2.DB2.table on a.key=b.key

So far, I have read many answers on this forum as well as on google but no luck any where..!!

2 Answers2

1

AFAIK this isn't possible as you can only run the query through one connector, which can only connect to one database server at a time. You'll need to run one query then run a second query and merge the results in PHP.

The only thing that comes remotely close is if you're connecting to two databases on the same host. This answer covers that.

An example of this would be:

$rowsA = $rowsB = [];
$mysqliA = new mysqli($hostA, $usernameA, $passwordA, $databaseA);
$mysqliB = new mysqli($hostB, $usernameB, $passwordB, $databaseB);

$query = "SELECT id, A1, A2, A3 FROM tableA";
$resultA = $mysqliA->query($query);
while($row = $resultA->fetch_assoc())
{
    $rowsA[$row['id']] = $row;
}

$query = "SELECT id, B1, B2, B3 FROM tableB";
$resultB = $mysqliB->query($query);
while($row = $resultB->fetch_assoc())
{
    $rowsB[$row['id']] = $row;
}

$all_rows = array_merge_recursive($rowsA, $rowsB);

Check out this eval.in example of the array_merge_recursive working.

Community
  • 1
  • 1
Styphon
  • 10,304
  • 9
  • 52
  • 86
1

Depending on how many records you want to join, it make take a lot of time to do that via code.

If yor're the DBA or the DBA is willing to help you, why don't you try with a linked server??

With a linked server, you can run the query in either of the servers with PHP, so you code will look something like this:

$query = "SELECT a.id_col, b.col, a.other_col 
FROM [SERVER1].[your_db].[dbo].your_table
INNER JOIN your_other_table b
ON a.id_col = b.id_col";

That way, you can run your query from either server.

If you're using SQL Server, you can do it like this or with SSMS, like this.

I've never created a linked server in MySQL, but in this link you can find how to do it.

Hope it helps.

Community
  • 1
  • 1
desouler
  • 26
  • 2