MySQL definition function rand

Source: Internet
Author: User

How do I get random numbers in a data range via MySQL?

MySQL itself provides a function called Rand, which returns a V range of 0 <= v < 1.0.

The MySQL document that describes this function also describes the way that can be calculated by this formula floor (i + RAND () * (J–i)), which obtains the random number V of I <= v < J.

Attached Document Link: Http://dev.mysql.com/doc/refman/5.0/en/mathematical-functions.html#function_rand

For the sake of writing and invoking, write a function to return random numbers, note that this function in order to comply with personal habits, is to use floor (i + RAND () * (J–i + 1)) Such a formula, the range of random number V is i <= v <= J, rather than I <= v < J.

CREATE FUNCTION rand_num (    integer,    integerRETURNSInteger  BEGIN    RETURNfloor+RAND*-  +1)); END;

For example, to get a random number of 1-9, this is called:

Select rand_num (19);

MySQL definition function rand

Related Article

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: info-contact@alibabacloud.com 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.