How to use the RAND () function to generate a random number instance in mysql

Source: Internet
Author: User
The mysqlRAND () function returns a random floating point value ranging from 0 to 1.0. If an integer parameter N is specified, it is used as a seed value. The random number sequence generated by each seed is different. This article describes how mysql uses the RAND () function to generate random number instances. For more information, see. The project needs to dynamically generate random numbers with fixed digits, such as 8-bit and 5-bit.

The method we saw earlier is as follows:


This is not accurate, and there is a probability that four digits will occur. the Rand () function is 0 ~ 1 (infinitely close) random function

If a random number is 0.05321

In this way, the conversion is 5321, with only four digits.

If you can wrap it with a function, when you find that the number of digits is incorrect after the value is obtained, it is perfect to fill in the bits.

The following is a function I modified, but the disadvantage is that the number of digits of the generated function cannot exceed 20. Of course, you can change it.

DELIMITER $$USE `prvecard`$$DROP FUNCTION IF EXISTS `getRand`$$CREATE DEFINER=`PECARD`@`%` FUNCTION `getRand`(counts INTEGER) RETURNS VARCHAR(20) CHARSET utf8BEGIN       DECLARE sTemp VARCHAR(20);    DECLARE sTempCounts INTEGER;       SET sTemp = CONCAT( ROUND(ROUND(RAND(),counts)*(POW(10,counts))),);        IF(CHAR_LENGTH(sTemp)

However, you have to randomly

update company set  directors=round(round(rand(),2)*1000),associate=round(round(rand(),2)*1000);

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.