I have the following scenario, I have a table and I need to make a select with an order by RAND (). But I'd like to put some conditions for example:
TABELA
ID | NOME | IDADE | GRUPO
Data
1 | Hiago | 20 | 1
2 | Igor | 15| 1
3 | Ana| 18 | 2
4 | Fernanda| 19 | 4
5 | João | 20 | 5
5 | Tati | 16 | 2
I would like to make a SELECT
with ORDER BY RAND()
but in this SELECT
I would put a LIMIT of 3 and I would like to ensure that these 3 have values of column GRUPO
repeated only if you do not have more records in the GRUPO
column.
What should happen
RETURN (CORRECT) COM LIMIT 3:
2 | Igor | 15| 1
3 | Ana| 18 | 2
4 | Fernanda| 19 | 4
RETURN (INCORRECT) WITH LIMIT 3:
1 | Hiago | 20 | 1
2 | Igor | 15| 1
4 | Fernanda| 19 | 4
The above return was incorrect because it repeated group 1 2 times and there were groups 2, 4 and 5 still to be displayed.
RETURN (CORRECT) COM LIMIT 5:
2 | Igor | 15| 1
3 | Ana| 18 | 2
4 | Fernanda| 19 | 4
5 | João | 20 | 5
1 | Hiago | 20 | 1
In this case it was correct because all the groups already appeared at least once so he repeated the code of group 1, but nothing would prevent him from repeating the 2 since they all appeared ...
So let's ask the question, how would I mount this SQL?