samedi 6 juin 2015

Select distinct random rows from db

I am trying to get 5 random rows from a table of questions and put into an array, but I want them to be distinct rows. Here is my current code which works in getting 5 random rows:

public List<List<String>> getAllAnswersByQuestion2() {
    List<String> array1 = new ArrayList<String>();    
    List<String> array2 = new ArrayList<String>();  

    array1.clear();
    array2.clear();

    SQLiteDatabase db = this.getReadableDatabase();

   Cursor c = db.query("questiondb",null,null,null,null,null,"RANDOM() limit 5");

   try {

    if (c!= null && c.moveToFirst())

   {
       do {

     String questdescr = c.getString(c.getColumnIndex(QDESCR));
     String answerSetIds = c.getString(c.getColumnIndex(ASID)); 

     array1.add(questdescr);
     array2.add(answerSetIds);

    } while (c.moveToNext());

 }

   List< List<String> > listArray = new ArrayList< List<String> >();

   listArray.clear();

   listArray.add(array1);
   listArray.add(array2);

   return listArray;

} finally {

        c.close();            
        db.close();
        }
}

I've tried the following code in place of the cursor:

    String selectQuery = "SELECT DISTINCT QDESCR, ASID FROM" +TABLE_QUESTION+ "ORDER BY RAND() LIMIT 5";

   Cursor c = db.rawQuery(selectQuery, null);

But this keeps giving me a generic syntax error. Can someone suggest how I may be able to amend my existing code to make this work.

Aucun commentaire:

Enregistrer un commentaire