How to use MySQL's random number function rand()

We all know that the random function rand or mt_rand can pass in one parameter to generate a random integer between 0 and the parameter, or pass in two parameters to generate a random integer between these two parameters.

In mysql, the random number function rand cannot pass parameters, and the generated floating-point numbers between 0 and 1, if we need to generate random integers greater than 1 in mysql, what should we do?

Such a demand is not unfamiliar. For example, the article system we made needs to cheat and randomly add an integer within a certain range to the page views of the article.

 

Now, suppose you need to generate random integers between 234 and 5678, how to implement it under mysql.

We can't change the value of rand under mysql, but we can change our needs,

1. We need a minimum of 234 and a maximum of 5678. The minimum generated by rand is 0 and the maximum is 1. Subtract 234 from the number we need to see?
The minimum number is 234 - 234 = 0, the maximum number is 5678 - 234 = 5444; hey, bright spot, the minimum number we need matches the minimum generated by rand.
We only need to let the function generate random numbers from 0 to 5444, and then add 234, which is our original requirement.
Our original requirement is described by a pseudo-expression, which will be

  1. round(rand(0,5444) + 234)

2. Now we just need to find a way to change our needs again, so that the minimum number is 0 and the maximum number is changed to 1.
Obviously, 5444 minus 5443 is 1, but in this way, the minimum number will be negative.
The minimum number is still 0, the maximum number is 1, too simple, 5444 / 5444 = 1 , 0 /5444 = 0
Now, the pseudo-expression of the original requirement is:

  1. round(rand(0,1) * 5444 + 234)

3. Remove the parameters of the pseudo-expression, just like rand under mysql, with the same effect. Rounding function we use rounding ROUND

Therefore, the final true mysql expression of our original requirement is

  1. ROUND(RAND() * 5444 + 234)

 

To summarize the idea:
1. Compare the difference between rand(x, y) and rand(0,1).
2. Transform
   rand(x,y) to rand(0,1) step by step rand(x,y) 
= rand(0, (yx)) + x 
= rand(0/(yx), (yx)/(yx )) * (yx) + x 
= rand() * (yx) + x

 

This is a very simple mathematical arithmetic formula. Using a simple example, I talked about some basic skills of the algorithm: reduce the requirements so that the knowledge you have mastered can meet the requirements.

 

Reference address: https://blog.csdn.net/zhangfeng1133/article/details/49848257

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324973162&siteId=291194637