MYSQL连接并查询2台不同服务器上的2个数据库
提前感谢你的帮助,
我已经花了一周的时间来让它工作,并在这个网站和其他网站上搜索了各种例子。我正在尝试连接同一台服务器上的2个数据库。
我可以分别从每个数据库中获取数据,但我不知道如何编写代码来合并/连接数据
这是我的错误代码,基于我在网上读到的大量帮助和如何发布。欢迎任何帮助或线索。如果我能把任何东西输出/打印出来,我会很高兴
// connect to db1 contact info
$host1='db1hostname';
$user1='db1user';
$password1='db1pw';
$database1='db1user';
// connect to db2, phone call info
$host2='db2hostname';
$user2='db2user';
$password2='db2pw';
$database2='db2user';
$connect1 = mysql_connect($host1, $user1, $password1) OR DIE
('Unable to connect to database! Please try again later.');
$connect2 = mysql_connect($host2, $user2, $password2) OR DIE
('Unable to connect to database! Please try again later.');
// i think this is where things start to go wrong
mysql_select_db($database1, $connect1);
mysql_select_db($database2, $connect2);
// i want to join these 2 tables from diff db by the caller info这是一个手机号码//数据库2信息来自电话记录表格,不能更改,所以我不能通过表格primary id连接这两个tbls,因为我永远不知道db2中的每个呼叫的id是什么,我希望通过主叫手机号码连接这两个db表格
$data = mysql_query("SELECT `m`.`id`, `m`.`created`, `m`.`caller`, `m`.`content_text`,
`c`.`iname`, `c`.`caller`
FROM database1.contacts c, database2.messages m
WHERE `c`.`caller` = `m`.`caller` ") or die(mysql_error());
// i then want to print the results to a table
while($info = mysql_fetch_array( $data )) 发布于 2013-10-11 23:01:27
连接到您的第一个数据库,当您想要在第二个数据库中运行查询时,只需使用如下代码中所示的简单方法。
$query = "SELECT t1.*, t2.*
FROM tableOfDB1 t1
LEFT JOIN database2.tableOfDB2 t2 ON t1.ID = ts2.TableOne_ID
";或者,如果您只想要来自db2的数据
$query = "SELECT t2.*
FROM database2.tableOfDB2 t2";在您的示例中,尝试如下所示
$data = mysql_query("SELECT `m`.`id` AS mID, `m`.`created` AS mCreated, `m`.`caller` AS mCaller, `m`.`content_text`,
`c`.`iname` AS cIname, `c`.`caller` AS cCaller
FROM database1.contacts c, database2.messages m
WHERE `c`.`caller` = `m`.`caller` ") or die(mysql_error());
while( $row = mysql_fetch_array($data) )
{
echo "<br>mCaller: ".$row['mCaller'];
echo "<br>cCaller: ".$row['cCaller'];
}发布于 2013-10-11 23:07:02
如果如您所说,数据库在同一台服务器上,那么您可以使用一个连接执行所有操作。您必须在查询中明确说明您的数据库名称,但这样您就可以以一种非常直接的方式完成所有其他操作。
请参阅https://stackoverflow.com/questions/19039718/reference-column-in-seperate-database/19040228#19040228
https://stackoverflow.com/questions/19321219
复制相似问题