我有两个表,他们的名字是个人资料和消息。我尝试从sql获取profileId相关的配置文件数据和最后一条消息。
SQLiteDatabase db = this.getReadableDatabase();
String selectQuery = "select " +
"profiles.profileId," +
"profiles.profileName," +
"profiles.profileImgPath," +
"profiles.profileStatus," +
"messages.messageContent," +
"messages.messageTime " +
"from profiles left join messages on profiles.profileId=messages.profileId " +
"group by profiles.profileId " +
"order by messages.messageId DESC;";
Cursor c = db.rawQuery(selectQuery, null);
Log.i("query",selectQuery);
if (c.moveToFirst()) {
do {
Log.i("gokberksql", c.getString(1) + "x" + c.getString(4));
} while (c.moveToNext());
}
gokberksql﹕ sinanxKanka naber
但需要返回
gokberksql﹕ sinanxIyi senden naber
此外,此查询在我的计算机编辑器中运行良好,但android结果不正确。
答案 0 :(得分:1)
您应该在查询中选择max messageTime。这将为您提供与包含最大值
的行相同的列的值String selectQuery = "select " +
"profiles.profileId," +
"profiles.profileName," +
"profiles.profileImgPath," +
"profiles.profileStatus," +
"messages.messageContent," +
"max(messages.messageTime) as messageTime " + // <- here
"from profiles " +
"left join messages on profiles.profileId = messages.profileId " +
"group by profiles.profileId" +
"order by profiles.profileId, messages.messageId DESC;";
请注意,此行为是在SQLite版本3.7.11中引入的,它在API 16(JellyBean)中成为标准。如果您需要支持API 15或更早版本,则可能必须使用其他查询。
答案 1 :(得分:0)
为什么你有一个profiles.profileId组,在你的情况下不需要,因为你没有对profileId组进行任何聚合。试试
String selectQuery = "select " +
"profiles.profileId," +
"profiles.profileName," +
"profiles.profileImgPath," +
"profiles.profileStatus," +
"messages.messageContent," +
"messages.messageTime " +
"from profiles left join messages on profiles.profileId=messages.profileId " +
"order by profiles.profileId, messages.messageId DESC;";