简体   繁体   中英

Using multiple tables to get data SQLitedatabase

I have three tables in my database: Category, Words, and WordImgs. I'm trying to implement ListgetAllCategories and the problem is I need to retrieve data from all three tables in order to do this. Am I suppose to join the 3 tables? Not quite sure how to accomplish this.

Each Category contains a name and an arraylist of words. Each word contains a name an arraylist of images.

Statements used to create tables:

public void onCreate(SQLiteDatabase db) {
    final String SQL_CREATE_CATEGORY_TABLE = "CREATE TABLE " + CATEGORIES_TABLE + " (" +
            _ID + " INTEGER PRIMARY KEY AUTOINCREMENT," +
            TITLE + " TEXT NOT NULL " + ");";
    final String SQL_CREATE_WORDS_TABLE = "CREATE TABLE " + WORDS_TABLE + " (" +
            _ID + " INTEGER PRIMARY KEY AUTOINCREMENT," +
            TITLE + " TEXT NOT NULL, " +
            BELONGS_TO + " INTEGER NOT NULL, " +
            "FOREIGN KEY (" + BELONGS_TO + ") REFERENCES " + CATEGORIES_TABLE + " (" + _ID + ")" +
            ");";
    final String SQL_CREATE_WORDIMG_TABLE = "CREATE TABLE " + WORDIMGS_TABLE + " (" + _ID + " " +
            "INTEGER PRIMARY KEY AUTOINCREMENT," + TITLE + " TEXT NOT NULL, " +
            BELONGS_TO + " INTEGER NOT NULL, " +
            "FOREIGN KEY (" + BELONGS_TO + ") REFERENCES " + WORDS_TABLE + " (" + _ID + ")" +
            ");";



    db.execSQL(SQL_CREATE_CATEGORY_TABLE);
    db.execSQL(SQL_CREATE_WORDS_TABLE);
    db.execSQL(SQL_CREATE_WORDIMG_TABLE);

}

you can join the 3 tables like this:

select *
from CATEGORIES_TABLE c
join WORDS_TABLE w on c.ID = w.BELONGS_TO
join WORDIMGS_TABLE wi on w.ID = wi.BELONGS_TO

You should really read up on joins :-)

You're actually mixing variables in with the SQL there, so I don't actually know what your column names and whatnot are, but I'll give you a quick-and-dirty example that should give you an idea.

Let's say you want all the image titles for words in the category "foo":

select wordimgs_table.title
from categories_table
inner join words_table on words_table.belongs_to = categories_table._id
inner join wordimgs_table on wordimgs_table.belongs_to = categories_table._id
where categories_table.title = 'foo'

This will give you basically an unordered list. Add in your own order by clause and friends. And obviously substitute the actual table and column names, etc etc.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM