简体   繁体   中英

How to correctly select a random row through a concret _id in SQLite

I've been developing an Android app and I'm using SQLite for a questions and answers database. Everything is working fine, but since I only know basics about SQL, I don't know what's the best approach to do what I want.

The app is basically a 15 question test, where each question has a category (there's 6 categories). The app has to ask at least one question from each category, since if it didn't, the result at the end would show 0 points at a never answered category, which would make no sense at all.

I actually can get it to work with the following code:

Question q = null;
for (int i = 0; i < NUM_CATEGORIES; i++) {
  q = dbHelper.getQuestion(question_ids, Integer.toString(i));
  questions.add(q);

  listAnswers = dbHelper.getAnswersFromQuestion(q.get_Id());
  all_answers.add(listAnswers);
}

NOTE: Parameters for getQuestion() are question_ids (ids of already asked questions, so I don't ask them again) and a String that represents the category (from 0 to NUM_CATEGORIES)

And this is the query I call (through the rawQuery() method) inside the getQuestion() method:

String queryQuestion= "SELECT * FROM Question WHERE Question.category = " + category + ";";

Where category is that String parameter I mentioned before that represents the actual category of the question to fetch.

But the problem that I'm having is that I'm always fetching the first question that has that category, and I'd like to fetch a random question with it.

For example, if I have this questions:

Question: "Question 1", Category: 0

Question: "Question 2", Category: 0

Question: "Question 3", Category: 1

Question: "Question 4", Category: 1

I would always get "Question 1" from Category 0, and "Question 3" from Category 1. And I would obviously like to get one randomly and not always the same one.

How can I can query this idea? Can I do something to fetch a question with that Category but not always the first one with it?

Thanks a lot!

You want a random row, so:

SELECT q.*
FROM Question q
WHERE q.category = " + category + "
ORDER BY random()
LIMIT 1;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM