简体   繁体   English

使用多个表获取数据SQLitedatabase

[英]Using multiple tables to get data SQLitedatabase

I have three tables in my database: Category, Words, and WordImgs. 我的数据库中有三个表:Category,Words和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. 我正在尝试实现ListgetAllCategories,问题是我需要从所有三个表中检索数据才能做到这一点。 Am I suppose to join the 3 tables? 我想加入3个桌子吗? 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: 您可以像这样加入3个表:

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. 您实际上是将变量与SQL混在一起,所以我实际上不知道您的列名和其他名称,但是我将给您一个简单的示例,该示例应该给您一个思路。

Let's say you want all the image titles for words in the category "foo": 假设您要为“ 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. 并且显然替换了实际的表和列名等。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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