[英]sqlite rawquery not working correctly
我有两个表,它们的名称分别是个人资料和消息。 我尝试从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结果不正确。
您应该在查询中选择最大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或更早版本,则可能必须使用其他查询。
为什么要有一个由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;";
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.