3
I have the following scenario, I have a table and I need to select an order by RAND(). But I would like to put some conditions for example:
TABELA
ID | NOME | IDADE | GRUPO
Dice
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’d like to make a SELECT
with the ORDER BY RAND()
but in that SELECT
I would put a LIMIT of 3 and I would like to ensure that in those 3 have column values GRUPO
repeated only if there are no further entries in the column GRUPO
.
What must happen
RETURN (CORRECT) WITH 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 return above was incorrect because he repeated the group 1 2 times and there were groups 2, 4 and 5 still to be shown.
RETURN (CORRECT) WITH 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 to repeat 2 since all appeared...
So let’s ask the question, how would I mount this SQL?