How to connect multiple database,servers in mysql and query from both tables of each other?

混江龙づ霸主 提交于 2019-12-24 15:18:24

问题


I am looking forward to connect two different database from different servers. Also, i would want to run a query that fetches data from both the database into a single result. Am doing this in PHP script with mysql. here is how am looking forward to do it [ without success :) ]

$dbh1 = mysql_connect('server1', 'uname', 'pwd')or die("Unable to connect to MySQL1"); 
$dbh2 = mysql_connect('server2', 'uname', 'pwd') or die("Unable to connect to MySQL2");

mysql_select_db('db1', $dbh1);
mysql_select_db('db2', $dbh2); //both will have same table name though

$qry = mysql_query("select * from db1.table1 where db1.table1.id='100' and db1.table1.id=db2.table1.id",$dbh1) or die(mysql_error());

$row= mysql_fetch_array($qry);

echo $row[2];

Am not getting any result or either error. Any help is appreciated, tnx.


回答1:


According to the PHP docs: http://il2.php.net/manual/en/function.mysql-query.php

"If the link identifier is not specified, the last link opened by mysql_connect() is assumed."

So in this case you're only retrieving data from $dbh2.

I don't think it's possible to do what you are trying to do with one query. You should merge the results after you get them.




回答2:


It doesn't work that way. You can use multiple databases in a single SQL query, but it always operates on one connection handle. If you need to connect to two different servers, you have to use two queries and merge data in PHP.



来源:https://stackoverflow.com/questions/9584810/how-to-connect-multiple-database-servers-in-mysql-and-query-from-both-tables-of

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!