0

Is it possible to select x random rows from a table, where one of the rows have to be a special row (thereby with a special field value) within one query?

Basically what I'm trying to create is a Guessing Game, where you have x amount of questions, with x amount of possible (checkbox selectable) answers!

This is how I select the answers currently... With 2 query's

$answers = 4; // This is the max amount of answers

// Just for testing the question_id is manually set

$query = "SELECT * FROM `answers` WHERE `question_id` = 0 AND `correct` != 1 ORDER BY RAND() LIMIT " . ($answers - 1) . "";
$query = "SELECT * FROM `answers` WHERE `question_id` = 0 AND `correct` = 1 LIMIT 1";

The "question_id" tells which question we are talking about, and the "correct" just tells if that field is the correct answer

So is it possible to select x random rows from a table, where one of the rows have to be "the correct one", within one query?

1
  • Did you try using the UNION clause? Commented Jul 14, 2013 at 3:18

2 Answers 2

1

may be use UNION ?

$answers = 4;

$query = "SELECT * FROM `answers` WHERE `question_id` = 0 AND `correct` != 1 ORDER BY RAND() LIMIT " . ($answers - 1) . "";

$query .= " UNION ";

$query .= "SELECT * FROM `answers` WHERE `question_id` = 0 AND `correct` = 1 LIMIT 1";

With one single query, you will be able to get the desired result

http://dev.mysql.com/doc/refman/5.0/en/union.html

Sign up to request clarification or add additional context in comments.

2 Comments

Damn, that gave me this error... Incorrect usage of UNION and ORDER BY
Ohh it needed to have parenthesis around each "query"
0
$query = "SELECT * FROM answers WHERE ... whatever ... AND `question_id` IN (5, 9, 12, 16, 2)

So, you first find the number of rows and then put the correct answer's ID in to the WHERE IN statement. Because you know the one you want, you can just surround it with random IDs from the table and then render them in a random fashion.

3 Comments

No, I don't know the answer's id, the only thing I know is the question_id and the amount of rows (answers) I want in return
Then generate random numbers inside the number of rows that exist
So you want me to make another query, to check for how many rows that exist, and then... well that didn't make it become only one query?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.