Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get one random record for each of 3 group

Tags:

mysql

I have a table with questions from three categories.

I get one random question by using the following:

SELECT * FROM tblQuestions ORDER BY RAND() LIMIT 1

But the table also have a field called qCategory where there are 3 categories in total. What I want is the SQL query to get one question from each of the 3 categories (so 3 random questions in total).

like image 403
janlindso Avatar asked Feb 18 '23 01:02

janlindso


1 Answers

You can combine the results of three queries by using UNION ALL:

(SELECT * FROM tblQuestions WHERE qCategory='A' ORDER BY RAND() LIMIT 1)
UNION ALL
(SELECT * FROM tblQuestions WHERE qCategory='B' ORDER BY RAND() LIMIT 1)
UNION ALL
(SELECT * FROM tblQuestions WHERE qCategory='C' ORDER BY RAND() LIMIT 1)
like image 179
Mark Byers Avatar answered Feb 20 '23 14:02

Mark Byers