There is a database with tables "books", "books_authors", "authors". "books_authors" is used to display many-to-many relationships. It is necessary to obtain from the database a list of books within which there will be authors. Here is how I do it:
public ArrayList<Book> getBooks() { Cursor booksCursor = mDB.rawQuery(TOP_SALES_BOOKS_QUERY, null); ArrayList<Book> books = new ArrayList<>(); if(booksCursor.moveToFirst()) { int idIndex = booksCursor.getColumnIndex(Book.ID_TAG); int nameIndex = booksCursor.getColumnIndex(Book.NAME_TAG); //... do { int bookId = booksCursor.getInt(idIndex); String bookName = booksCursor.getString(nameIndex); //... Cursor authorsBooksCursor = mDB.rawQuery(AUTHORS_BY_BOOK_ID_QUERY, new String[] {String.valueOf(bookId)}); ArrayList<Author> authors = new ArrayList<>(); if(authorsBooksCursor.moveToFirst()) { int authorNameIndex = authorsBooksCursor.getColumnIndex(Author.NAME_TAG); do { String authorName = authorsBooksCursor.getString(authorNameIndex); authors.add(new Author(authorName)); } while (authorsBooksCursor.moveToNext()); } authorsBooksCursor.close(); books.add(new Book(bookId, bookName, authors, ...)); } while (booksCursor.moveToNext()); } booksCursor.close(); return books; } The method is executed ~ 40 seconds. If you don’t get authorsBooksCursor, then ~ 1 second. How can I improve a method or query for faster execution?
Here are the queries themselves:
String TOP_SALES_BOOKS_QUERY = "SELECT * FROM " + Book.TABLE_NAME; String AUTHORS_BY_BOOK_ID_QUERY = "SELECT BAT." + DEFAULT_ID_TAG + ", AT." + Author.NAME_TAG + " FROM " + BOOKS_AUTHORS_TABLE_NAME + " AS BAT INNER JOIN " + Author.TABLE_NAME + " AS AT ON BAT." + Author.ID_TAG + " = AT." + Author.ID_TAG + " WHERE BAT." + Book.ID_TAG + " = ?";
books_authors, sort by book title, and add authors to the book sequentially. So there will be one request. - Vladyslav Matviienko