[英]MySQL,JDBC query execution too long
I've got database querying that has become too slow with my current implementation.我的数据库查询在我当前的实现中变得太慢了。 I need to get all movies from a database and for each of these movies i need their file data from another table.我需要从数据库中获取所有电影,并且对于这些电影中的每一个,我都需要从另一个表中获取它们的文件数据。 So for each movie i am doing another query.所以对于每部电影我都在做另一个查询。 For each candidate entry i need to do a comparison to every movie in the database.对于每个候选条目,我需要与数据库中的每部电影进行比较。 Should this be taking 5-10 seconds to execute for approximately 500 candidates?对大约 500 名候选人执行这是否需要 5-10 秒?
// get movies with all their versions
private ArrayList<Movie> getDatabaseMovies(Connection conn) throws Exception {
PreparedStatement getMoviesStmt = conn.prepareStatement("SELECT movieid, title FROM movies", Statement.RETURN_GENERATED_KEYS);
ArrayList<Movie> movies = new ArrayList<Movie>();
try {
ResultSet rs = getMoviesStmt.executeQuery();
while (rs.next()) {
Movie movie = new Movie(rs.getString(2), getDatabaseMovieFiles(conn, rs.getInt(1)));
movies.add(movie);
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
getMoviesStmt.close();
}
return movies;
}
public ArrayList<MovieFile> getDatabaseMovieFiles(Connection conn, int movieID) throws Exception {
ArrayList<MovieFile> movieFiles = new ArrayList<MovieFile>();
PreparedStatement stmt = conn.prepareStatement("SELECT filename, size, hash, directory FROM file_video WHERE movieid = ?");
try {
stmt.setInt(1, movieID);
ResultSet rs = stmt.executeQuery();
while (rs.next()) {
MovieFile movieFile = new MovieFile(rs.getString(1), rs.getLong(2), rs.getBytes(3), rs.getString(4));
movieFiles.add(movieFile);
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
stmt.close();
}
return movieFiles;
}
Should this be taking 5-10 seconds to execute for approximately 500 candidates?对大约 500 名候选人执行这是否需要 5-10 秒?
Probably not.可能不是。
There are two ways to improve this:有两种方法可以改善这一点:
Make sure that there is an index on the movieid
column of file_video
.确保 file_video 的movieid
列上有file_video
。
Combine the two queries into one by using a JOIN
.使用JOIN
将两个查询合并为一个。
You probably should do both.你可能应该两者都做。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.