我想得到随机数据而不重复

时间:2014-07-28 06:35:48

标签: android sqlite

我想从数据库(sqlite)获取随机数据而不重复。任何人都可以帮助我..

    DBManager *databaseManager = (DBManager *)[[DBManager alloc] init];
NSArray *array=[databaseManager readQuestionFromDatabase];
que=[array objectAtIndex:0];
self.lblQuestion.text=que.question;
[self.btnOption1 setTitle:que.questionoption1 forState:UIControlStateNormal];
[self.btnOption2 setTitle:que.questionoption2 forState:UIControlStateNormal];
[self.btnOption3 setTitle:que.questionoption3 forState:UIControlStateNormal];
[self.btnOption4 setTitle:que.questionoption4 forState:UIControlStateNormal];

2 个答案:

答案 0 :(得分:0)

使用Random Number Generation via javaROWNUM for SQLITE的方法可以帮助您。但您可能需要多次执行查询。

int DBSize =  getDBSize(); 
int randomRowNum = 0;

ArrayList<Integer> list = new ArrayList<Integer>(size);
for(int i = 1; i <= size; i++) {
    list.add(i);
}

Random rand = new Random();
while(list.size() > 0) {
    int index = rand.nextInt(list.size());
    randomRowNum = list.remove(index);
    selQuery = "SELECT * FROM MYTABLE WHERE ROWNUM = " + randomRowNum + " ORDER BY SOME_UNIQUE_SORT_ORDER";
    // EXECUTE SELECT QUERY AND YOU WOULD GET RANDOM ROWS here.

}

private int getDBSize ()
{
    int retVal = 5;
    retVal = // Select count(1) from myTable;
    return retVal; //(Assuming I have 5 records in DB)
}

注意:确保ORDER BY中的排序顺序是唯一的。其他结果将不如预期。

答案 1 :(得分:0)

这是另一个使用相同随机数生成而不重复但避免多次查询执行的答案。

String randomRowData = "";

selQuery = "SELECT MYFIELD FROM MYTABLE ";
ArrayList<String> list = new ArrayList<Integer>(size);
for(int i = 1; i <= size; i++) {
    list.add(MYFIELD_VALUE); // All DB Data here
}

Random rand = new Random();
while(list.size() > 0) {
    int index = rand.nextInt(list.size());
    randomRowData = list.remove(index);  // Will display the rows without repetition
    /* USE THE ROW DATA APPROPRIATELY */
}