如何使用managedQuery连接多个表?

时间:2010-11-29 16:23:29

标签: android sqlite android-contentprovider

我正在尝试进行查询,从两个表中获取数据,但不会向我显示任何结果。我知道有结果,因为在SQLite3中它至少显示一个,例如

sqlite> select eventthemename, eventtypename from event_type, event_theme
   ...> where event_type.eventthemes = event_theme._id     
   ...> and event_type._id = '2';
Tribal | Dance

我正在使用内容提供商。有没有人知道如何制作这个?

2 个答案:

答案 0 :(得分:0)

您的问题不是很清楚(您应该包含一些代码!),因此我可能无法按您的意愿回答您的问题。但是下面是一个简单的例子,我在一个查询中连接两个表:

private static final String QUERY_ALL_COURSES_WITH_SEMESTER =
 "SELECT * FROM Course JOIN Semester ON semesterId = courseSemesterId";

public Course getCourseByCodeAndSemester(String courseCode, Semester semester)
{
 Course result = null;
 String whereClause = " WHERE courseCode = '" + courseCode.toUpperCase() + "'"
   + " AND semesterId = " + semester.getInternalId();
 Cursor cursor = db.rawQuery(QUERY_ALL_COURSES_WITH_SEMESTER + whereClause, null);
 if (cursor.moveToFirst())
 {
  result = Course.createFromCursor(cursor);
 }
 cursor.close();
 return result;
}

请注意,在此功能中可能有许多内容可以优化,但它说明了如何完成。

答案 1 :(得分:0)

当我使用内容提供商时,我结束了做不太快但不起作用的事情:

themes = managedQuery(
        EventTheme.CONTENT_URI,
        PROJECTIONTHEMES,
        EventTheme.EVENTTYPE + "= ?",
        new String[] {eventType},
        EventTheme.DEFAULT_SORT_ORDER);

String[] from = new String[] { 
        Event._ID,
        Event.NAME,
        Event.STARTDATE,
        Event.ENDDATE,
        PointOfInterest.POINTOFINTERESTNAME
    };

int[] to = new int[] { 
        R.id.event_id,
        R.id.name,
        R.id.start_date,
        R.id.end_date,
        R.id.location_name
    };

while (themes.getPosition() < themes.getCount() - 1) {
    themes.moveToNext();
    eventTheme = themes.getString(themes.getColumnIndexOrThrow(EventTheme._ID));                
    events = managedQuery(
            Event.CONTENT_URI,
            PROJECTIONEVENTS,
            Event.EVENTTHEME + "= ?",
            new String [] { eventTheme } ,
            Event.DEFAULT_SORT_ORDER);
}