androidsqlsqlitejoin

How do I join these tables to relate chapters, sub-chapters and text entries?


My book reader app has database tables chapters (columns id and name), subchapters (columns id and number), and entries (columns id and text).

A rawQuery for a text entry works. However when the text displays, I need the chapter name and subchapter number as well (and the subchapter for the user to navigate). I need to JOIN but I am not understanding it.

rawQuery:

public List<String> getRandomTextEntry() {
    List<String> list = new ArrayList<>();
    Cursor cursor = database.rawQuery("SELECT * FROM entries ORDER BY
RANDOM() LIMIT 1", null);
    cursor.moveToFirst();
    while (!cursor.isAfterLast()) {
        list.add(cursor.getString(1));
        cursor.moveToNext();
    }
    cursor.close();
    return list;
}

Solution

  • Why are you want to use multiple tables? In my opinion, it is better to have only one table with the following columns: id, chapter, subchapter, and text. Of course, you have to use the same chapter name and maybe the same subchapter numbers multiple times but then you do a text column query and in that case, at the same time, you can get which chapter it is and which subchapter. This tutorial describes really good how to handle multiple columns: https://www.androidhive.info/2011/11/android-sqlite-database-tutorial/

    But if you still want to use multiple tables and "link" them, I would suggest following this tutorial: https://www.androidhive.info/2013/09/android-sqlite-database-with-multiple-tables/ It is basically doing exactly the same what you want.