如何将来自两个单独表的数据合并为一个Cursor?

时间:2013-07-24 19:30:21

标签: android sqlite android-sqlite

目前,我有一个帖子表和一个用户表。当然,每个用户可以与多个帖子相关联。 post表中的每一行都存储创建帖子的用户的用户ID。以下是示例行:

发布行:post_id标题user_id

用户行:user_id user_name

我希望通过将post表中的用户ID与user表中的用户ID相匹配来返回包含post行及其相应用户行的Cursor。我将使用什么类型的查询来实现此目的?结果应该是:

合并行:post_id标题user_id user_name

更一般地说:如何将基于共享数据的两个独立表中的数据合并到一个Cursor中?

2 个答案:

答案 0 :(得分:10)

您可以使用CursorJoiner来获得类似于将两个Cursor合并为一个的东西。 CursorJoiner实际上不执行合并。在迭代它时,它会移动原始的两个游标,使它们的行在指定的列上匹配。这就是为什么必须在要在连接中使用的列上对两个游标进行排序。

文档链接:http://developer.android.com/reference/android/database/CursorJoiner.html

代码示例:

CursorJoiner joiner = new CursorJoiner(userCursor, new String[]{ "user_id" }, postCursor, new String[] {"user_id"});

while (joiner.hasNext()) {
    CursorJoiner.Result result = joiner.next();
        switch (result) {
            case LEFT:
                // don't care about this case
                break;

            case RIGHT:
                // nor this case
                break;

            case BOTH:
                // here both original Cursors are pointing at rows that have the same user_id, so we can extract values
                int postId = postCursor.getInt(...);
                String headline = postCursor.getString(...);
                int userId = userCursor.getInt(...);        
                String userName = userCursor.getString(...);

                // do something with above values

                break;

        }
}     

答案 1 :(得分:8)

您还可以在Android代码中使用原始SQLite语句,如:

SQLiteDatabase db = this.getReadableDatabase();
    Cursor cursor = db.rawQuery("SELECT serials.id, serials.cabinet_number, serials.serial_number, " +
            "configuration.frequency, configuration.ag, configuration.number_alarms, configuration.failed_rapper, configuration.max_mv, configuration.max_nav " +
            "FROM serials JOIN configuration ON serials.id = configuration.serial_id WHERE serials.id = '" + current_id + "'", null);
    cursor.moveToFirst();

在SELECT中,格式为table_name.column_name。 ON是您根据共享数据组合数据的地方。

相关问题