I build a website where i need to choose random-weighted record from database.
There is a snipped of code in SQL : select one row randomly, but taking into account a weight
SELECT t.*, RAND() * t.weight AS w
FROM table t
ORDER BY w DESC
LIMIT 1
It works fine on small sample of records.
When trying on close to 1 mln records it gets slow ( 1.3 - 1.8 second) on my local machine, and i guess that i would take even longer on even bigger sets.
How could it be optimised? Are there better ways to randomly choose weighted record?
My attempt at it would be to calculate the weights on regular basis, store them in separate table, choose random number programmaticaly and search for closest record to this number.