1

I have names in my database and I want to draw a name for a contest.

Anyone have an idea for that ?

Thanks !!

Sarah L.
  • 85
  • 1
  • 5

2 Answers2

2

A query like this could work

SELECT * FROM `table` WHERE id >= (SELECT FLOOR( MAX(id) * RAND()) FROM `table` ) ORDER BY id LIMIT 1;
heldt
  • 4,166
  • 7
  • 39
  • 67
2
SELECT * FROM table WHERE num_value >= RAND() * (SELECT MAX(num_value) FROM table) LIMIT 1

This works in constant time, regardless of the table size, if num_value is indexed. One caveat: this assumes that num_value is equally distributed in the range 0..MAX(num_value). If your dataset strongly deviates from this assumption, you will get skewed results (some rows will appear more often than others).

NullPoiиteя
  • 56,591
  • 22
  • 125
  • 143
  • 1
    Thanks, it's exactly what I needed ! I tried to do that in pure php, but your idea is much better ! – Sarah L. May 07 '12 at 09:08