2012-12-24 134 views
2

我想调用两个不同数据库的表一次数据库的表A包含用户ID和数据库表B包含用户位置与用户ID,所以我想加入这两个表并获取与user_id.database A和B对应的位置在两个不同的服务器中。所以我怎么可以加入这两个表。如果它不可能加入这个,是否有任何有效的方法来做到这一点。请help.i'm尝试使用java,mysql来做到这一点。调用两个数据库服务器的最佳方式

ps = con.prepareStatement("SELECT user_id FROM A.users"); 
rs = ps.executeQuery(); 
while(rs.next()) 
    { 
    //call select statement for database B to get the location for each user id    

    } 

请提出一个有效的方式来做到这一点

Id User_id 
=========== 
1 44 
2 23 

User_id  location 
==================== 
44   india 
23   us 
+1

我想澄清一下:不同的数据库服务器/不同的数据库模式? – Raptor

+1

数据库是否在同一个mysql-server-instance上? –

+0

@PeterRader * A和B在两个不同的服务器*可能这个Sentece澄清你的问题。 –

回答

2

假设user_idlong

PreparedStatement psUserLocation = conB.prepareStatement("SELECT location FROM B.users WHERE user_id = ?"); 
while(rs.next()) { 
    //call select statement for database B to get the location for each user id 
    long userId = rs.getLong(user_id); 
    psUserLocation.setLong(1, userId) 
    ResultSet userLocation = ps.executeQuery(); 
    // Do whatever with the location(s) 
} 

编辑:为所有用户,而不是每个用户一个查询一个查询:

private final static String QUERY = "SELECT user_id, location FROM B.users WHERE user_id IN (%a)"; 

StringBuilder userList = new StringBuilder(); 
while(rs.next()) { 
    long userId = rs.getLong(user_id); 
    userList.append(userId); 
    if (!rs.isLast()) { 
     userList.append(","); 
    } 
} 

String usersLocationQuery = QUERY.replaceAll("%a", userList.toString()); 
PreparedStatement psUsersLocation = conB.prepareStatement(usersLocationQuery); 
ResultSet usersLocation = psUsersLocation.executeQuery(); 
// Do whatever with the locations 

请记住,这可能会失败/工作错误的,因为大多数DB有多少商品的限制的子句可以包含SQL IN。另外,这第二种方法可能允许在%a替代品上进行SQL注入。

+0

所以在这种情况下,如果有1000个用户ID,那么查询将执行1000次,有没有什么方法可以批量执行这个查询? – ishk

+0

为所有用户的一个查询编辑。 – m0skit0

+0

感谢这个解决方案,user_ids的数量可以变化,我不能限制它,你知道任何其他方式来实现这一点,没有任何限制。 – ishk

2

您可以使用FEDERATED Storage Engine。 FEDERATED存储引擎允许您从远程MySQL数据库访问数据,而无需使用复制或群集技术。查询本地FEDERATED表会自动从远程(联合)表中提取数据。没有数据存储在本地表上。这可能不是非常有效,但它会完成这项工作(JOINs)。

+0

+1因为ACID后面的解决方案是“最好的方式” –

1

如果您可以取消加入,一种可能的方法是一次性从tableA中获取所有user_id,然后将user_id一次性传递给tableB。当然,这种方法也需要你改变代码。

喜欢的东西:

select user_id from tableA (of databaseA); 

select user_id, location from tableB (of database B) where user_id in (<result_from_above_query) 

上述过程将需要两个查询。

相关问题