Problem with RAND in SQL

Asked

Viewed 63 times

1

I am using Mysql "5.6.38-log - Mysql Community Server (GPL)"

I have a trial that runs every second, and in it has a validation with a RAND:

WHERE t.auc_due_time < GREATEST(LEAST(TRUNCATE(12 * RAND(),0),12),2)

The problem I am facing is that it is always running the query in 5 OR 7 in this Rand, I need it to be always alternating, for example 11,9,3,5,2,7,10,11 etc..

Why isn’t it working that way? Is there some other way to do this?

1 answer

1

According to the Mysql documentation, the function RAND([N]), return a floating point between 0 and 1.0. To get a random integer R being i <= R < j, you need the following expression

FLOOR(i + RAND() * (j − i))

For example, for obiter an integer randomic between 7 and 12, use the following code (7 <= R < 12)

SELECT FLOOR(7 + (RAND() * 5));

An integer between 0 and 100 would be next:

SELECT FLOOR(0 + (RAND() * 100));

or

SELECT FLOOR((RAND() * 100));

For a random 2 to 12, you have to do the following:

SELECT FLOOR(2 + (RAND() * 11));

See the example execution on SQL Fiddle

  • In case it would be that way for an interval of 2 to 12? WHERE t.auc_due_time < FLOOR(2 + (RAND() * 10));

  • That’s right there.

  • Well, I did it that way, but it doesn’t seem to work either. Just to clarify better, it is running along with a regressive chronometer of 15 seconds, then I need it to execute the query in the seconds of 2 to 12 alternating always...

  • I made an issue in my reply

  • thanks for the reply.. And how would it be to do between 1 and 12?

  • would just put SELECT FLOOR(1 + (RAND() * 11));

  • How can I change this command so that it randomly generates the numbers and the number 1 appears more frequently?

Show 2 more comments

Browser other questions tagged

You are not signed in. Login or sign up in order to post.