Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get mysql random integer range?

Tags:

random

mysql

I am trying to generate a random integer for each row I select between 1 and 60 as timer.

SELECT downloads.date, products.*, (FLOOR(1 + RAND() * 60)) AS timer 

I have searched and keep coming up to this FLOOR function as how to select a random integer in a range. This is giving me a 1 for every row. What am I missing?

I am on mysql 5.0.75

Heres the rest of the query I belive it might be a nesting issue

SELECT * FROM (  SELECT downloads.date, products.*, FLOOR(1 + (RAND() * 60)) AS randomtimer,   (  SELECT COUNT( * )  FROM distros  WHERE distros.product_id = products.product_id  ) AS distro_count,   (SELECT COUNT(*) FROM downloads WHERE downloads.product_id = products.product_id) AS true_downloads   FROM downloads  INNER JOIN products ON downloads.product_id = downloads.product_id ) AS count_table WHERE count_table.distro_count > 0 AND count_table.active = 1 ORDER BY count_table.randomtimer , count_table.date DESC LIMIT 10 
like image 507
kevzettler Avatar asked Jun 11 '09 23:06

kevzettler


People also ask

How can we get a random number between 1 and 100 in MySQL?

select FLOOR( RAND() * (maximumValue-minimumValue) + minimumValue) as anyVariableName; Let us check with some maximum and minimum value. The maximum value we are considering is 200 and minimum is 100. The random number will be between 100 and 200 including 100 and 200 itself.

What is rand () in MySQL?

RAND() Return a random floating-point value.


2 Answers

This is working for me. Your mysql version maybe?

SELECT id, (FLOOR( 1 + RAND( ) *60 )) AS timer FROM users LIMIT 0 , 30 
like image 69
Ryan Oberoi Avatar answered Sep 23 '22 07:09

Ryan Oberoi


The output of the RAND function will always be a value between 0 and 1.

Try this:

SELECT downloads.date, products.*, (CAST(RAND() * 60 AS UNSIGNED) + 1) AS timer 
like image 24
Chris Morley Avatar answered Sep 19 '22 07:09

Chris Morley