2009-05-04 80 views
30

我有一个使用本地sqlite数据库的android应用程序。android:查询中的ORDER BY

private SQLiteDatabase mDb; 

当我运行此查询得到我的光标放在与PID等于ID行,根据需要:

mDb.query(true, PT_TABLE, new String[] {KEY_PID, KEY_TID}, 
    KEY_PID+" = "+id, null, null, null, null, null);   
当我运行下面的查询,目标是获得相同的结果集

,有序通过PID我得到 “android.database.sqlite.SQLiteException:数据类型不匹配

mDb.query(true, PT_TABLE, new String[] {KEY_PID, KEY_TID}, 
    KEY_PID+" = "+id, null, null, null, null, KEY_PID+" DESC"); 

任何想法?

回答

36

看起来你有点混淆了。根据SQLiteDatabase.query文档,最后一个参数是LIMIT子句。倒数第二个是ORDER BY条款。

Cursor query (boolean distinct, 
      String table, 
      String[] columns, 
      String selection, 
      String[] selectionArgs, 
      String groupBy, 
      String having, 
      String orderBy, // <-- ORDER BY 
      String limit) 

编辑

不过,也有另一种SQLiteDatabase.query其中ORDER BY将是最后

Cursor query (String table, 
      String[] columns, 
      String selection, 
      String[] selectionArgs, 
      String groupBy, 
      String having, 
      String orderBy) 
+8

在本文档中也有看起来是一个版本:SQLiteDatabase.query(表,列,选择,selectionArgs两个,GROUPBY,HAVING排序依据)< - 请注意一个字段(限)丢失 – 2012-06-05 23:01:44

+0

这是不对的,提到doc还给出了以下调用`查询(String table,String [] columns,String selection,String [] selectionArgs,String groupBy,String having,String orderBy)`。 – 2ndGAB 2016-03-04 13:26:50

7
KEY_PID + " = " + "'" + id + "'" 
23

这为我工作

String filter = MySQLiteHelper.JOB_ID + "=" + Integer.toString(jobID); 
String orderBy = MySQLiteHelper.LOG_TIME + " DESC"; 
Cursor cursor = database.query(MySQLiteHelper.LOG_TABLE_NAME, logTableColumns, 
     filter, null, null, null, orderBy); 
4

由于Orderby是查询中倒数第二个参数; 您的查询会是这样

mDb.query(true, PT_TABLE, new String[] {KEY_PID, KEY_TID}, 
    KEY_PID+" = "+id, null, null, null, KEY_PID+" DESC", null); 
2

如果我理解正确的话您的问题,试试这个。

String[] columns = new String[] {KEY_PID, KEY_TID}; 
    String where = KEY_PID + " = " + Integer.toString(id); 
    String orderBy = KEY_PID + " DESC"; 

    Cursor cursor = mDb.query(PT_TABLE, columns, where, null, null, null, orderBy);