Hello everybody,
I need an advice for query which must Select rows from table grouped by position but for each position get each time random rows. I’m not sure that I’m explaining clearly so I will do some example. Sorry for my bad English. So the example is:
This table could be several thousand rows, position will be only from 1 - 6. The big problem is that each day this select will be executed approximately 100 million times. So I need better optimazed query.
table ‘myTable’
id, position, name, userid
1 , 1 , foo, 20
2 , 1 , bar, 322
3 , 1 , foo, 322
4 , 2 , bar, 20
5 , 2 , foo, 45
6 , 2 , bar, 45
7 , 3 , bar, 20
8 , 3 , foo, 45
9 , 3 , bar, 45
10 , 4 , bar, 20
11 , 4 , foo, 45
12 , 4 , bar, 45
13 , 5 , bar, 20
14 , 5 , foo, 45
15 , 5 , bar, 45
16 , 6 , bar, 20
17 , 6 , foo, 45
18 , 6 , bar, 45
I need to SELECT each time only six rows group by position order by random.
The query :
SELECT id, position, name FROM myTable GROUP BY position ORDER BY RAND();
will be extremely slow for my needs
I have an idea to use some kind of UNION but I need best solution because load of the database is heavy. I’ll appreciate anybody who can help me! Thanks in advance.