Selecting multiple sets of rows with a single sql query

I have a question table outlined as follows.

id | question | answer | program | difficulty

I want to create an SQL statement that selectively selects 5 questions for each of the individual programs when the difficulty is simple.

So, if there are 4 programs, I will have 20 questions.

I thought something like this ...

SELECT * FROM questions WHERE difficulty='easy' AND syllabus IN ( SELECT DISTINCT syllabus FROM questions WHERE difficulty='easy' ) LIMIT (5* ( SELECT COUNT(DISTINCT syllabus) FROM questions WHERE difficulty='easy' ) 

But this does not return 5 from each individual line, only the correct number of questions from any curriculum.

+4
source share
1 answer

This will work, but will be very slow:

 SELECT * FROM questions WHERE difficulty='easy' ORDER BY RAND() LIMIT 5; 

It is best to select 5 IDs first, and then get the strings matching those identifiers. The identifier itself can be selected using the identifier WHERE> RAND (0, MAX (ID)), but if there are spaces, your data will be distorted.

A better alternative is discussed here, but more effort is required: Simple random samples from the Sql database

+1
source

All Articles