如何使用JDBC减少查询时间?

时间:2012-05-14 07:28:01

标签: java mysql

我使用Java(JDBC)从MySQL数据库中获取记录。我有桌子 - Stop_Times有150万条记录和 停止了1个lac记录。

我正在使用以下代码

ResultSet rs = stm.executeQuery("select distinct(stop_id) from Stop_Times force index (idx_stop_times) where agency_id = '" + agency_id + "' and route_type = " + route_type + " order by stop_id");

while(rs.next())
{
  stop_id.add(rs.getString("stop_id"));               
}

JSONArray jsonResult = new JSONArray();

String sql = "select * from Stops force index (idx_Stops) where stop_id = ? and agency_id = ? and location_type = 0 order by stop_name";

                  PreparedStatement pstm = con.prepareStatement(sql);

                  int rid = 0;

                  for(int r = 0; r < stop_id.size(); r++)
                  {
                      pstm.setString(1, stop_id.get(r).toString());
                      pstm.setString(2, agency_id);
                      rs = pstm.executeQuery();

                      if(rs.next())
                      {
                          JSONObject jsonStop = new JSONObject();
                          jsonStop.put("str_station_id", rs.getString("stop_id"));
                          jsonStop.put("str_station_name", rs.getString("stop_name") + "_" + rs.getString("stop_id"));
                          jsonStop.put("str_station_code", rs.getString("stop_code"));
                          jsonStop.put("str_station_desc", rs.getString("stop_desc"));
                          jsonStop.put("str_station_lat", rs.getDouble("stop_lat"));
                          jsonStop.put("str_station_lon", rs.getDouble("stop_lon"));
                          jsonStop.put("str_station_url", rs.getString("stop_url"));
                          jsonStop.put("str_location_type", rs.getString("location_type"));
                          jsonStop.put("str_zone_id", rs.getString("zone_id"));

                          jsonResult.put((rid++), jsonStop);
                      }                               
                  }

第一个查询返回6871条记录。但这需要花费太多时间 - 在服务器端需要8-10秒,在客户端需要40-45秒。

我想减少服务器端300-500毫秒和客户端10秒左右的这些时间。 请有人帮我解决这个问题吗?

2 个答案:

答案 0 :(得分:1)

您的策略是使用第一个查询来获取ID,然后循环这些ID并对第一个查询找到的每个ID执行另一个查询。实际上,您正在进行“手动”连接,而不是让数据库为您执行此操作。您可以在一个查询中重写所有内容:

select * from Stops stops
inner join Stop_Times stopTimes on stopTimes.stop_id = stops.stop_id
where stops.stop_id = ? 
  and stops.agency_id = ? 
  and stops.location_type = 0 
  and stopTimes.agency_id = ? 
  and stopTimes.route_type = ?
order by stops.stop_name

答案 1 :(得分:0)

尝试获取与您的请求相关的解释计划(参见http://dev.mysql.com/doc/refman/5.0/en/using-explain.html);避免全表扫描(解释加入ALL)。然后添加相关索引。然后重试。