开发者

Fetching random rows using a random index and RAND( )

开发者 https://www.devze.com 2023-01-16 03:01 出处:网络
I\'m using the following code to return a random row from a table. Using the field \'rand\'. S开发者_StackOverflow中文版ELECT *

I'm using the following code to return a random row from a table. Using the field 'rand'.

S开发者_StackOverflow中文版ELECT * 
FROM  imgs
WHERE rand > RAND( ) 
ORDER BY rand ASC 
LIMIT 1

The field 'rand' is generated by mysql at creation using something similar to:

INSERT INTO imgs SET rand = RAND ()

For some reason the results although changing each run are only rows with a very low 'rand' field. There is definitely a complete range with over 7,000 rows. Seams to work fine if i replace the 'WHERE rand > RAND( )' with 'WHERE rand > [a number between 0-1]'


RAND() generates a floating point value x where 0 <= x < 1.0... to generate a larger number (whole number) use FLOOR(y + (RAND() * z)) which will generate a value x where y <= x < (y+z)

0

精彩评论

暂无评论...
验证码 换一张
取 消