2

Let me start off first by saying I code php as a hobby and don't know a whole lot. That be said I'm having trouble with coming up with a clever way to perform a particular type of query.

Say I have dynamic quiz application that uses a database of test questions of three different subjects; 200 algebra, 100 history, 50 science. The user can select which and how many subjects they wish to have in their quiz and also choose how many questions that will be in the quiz.

Below is the working code I'm using now...

$sql = "SELECT *
        FROM quiz
        WHERE keyword LIKE '$algebra'
        OR keyword LIKE '$history'
        OR keyword LIKE '$science'        
        ORDER BY RAND() LIMIT $amount";

However the only issue with this code is that if I select 10 questions on my test I will have mostly algebra questions, a few history and no science questions. I'd like it so each subject selected is represented equally.

I think I might have bitten off more than I can chew with this project.

0

2 Answers 2

1

Just a guess:

$equal = $amount/3; // do your best to round this...
$sql = "SELECT * FROM quiz WHERE keyword LIKE '$algebra' ORDER BY RAND() LIMIT $equal
UNION
SELECT * FROM quiz WHERE keyword LIKE '$history' ORDER BY RAND() LIMIT $equal
UNION
SELECT * FROM quiz WHERE keyword LIKE '$science' ORDER BY RAND() LIMIT $equal";
Sign up to request clarification or add additional context in comments.

2 Comments

This will work only if the number of questions selected are less than 150. If the user selects more than 150 questions, then this query will not return the expected number of results, since there are only 50 science questions.
The maximum number to retrieve is another problem you could manage before the sql query by other means like knowing what keyword has the less records then calculate your number to retrieve according to this
0

@poozolax gave you a precise solution. You could get another one trying to compensate distribution by doing something like:

$sql = "SELECT * FROM
        (SELECT *,
        case 
             when keyword like '$algebra' then 350/200
             when keyword like '$history' then 350/100
             when keyword like '$science' then 350/50
        end * RAND() as ORD
        FROM quiz
        WHERE keyword LIKE '$algebra'
        OR keyword LIKE '$history'
        OR keyword LIKE '$science'        
        ) AS X ORDER BY ORD DESC LIMIT $amount";

I have no idea if default RAND() gives it's best to distribute evenly, however a tuning coefficient as 350/50 may give better chance to science.

Comments

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.