Code for generating random numbers using rand in MySQL

Source: Internet
Author: User
Tags mysql tutorial

The code to randomly generate a string is as follows:

Define a random string method in the mysql tutorial, and then call this method in the SQL statement.

Method for defining random string functions:
Select round (rand (), 4) * 10000 );
You can simply do this without using a function.

If you have to write a function
Delimiter $

Create
Function get_rand ()
Returns int deterministic
Begin
Declare return_no int;
Select round (rand (), 4) * 10000) into return_no;
Return return_no;
End $

Delimiter;

Example of using a random string function:
Update demotable set demoname = rand_string (32) where id> 23
Run the command directly.


At the beginning of the test, because I did not add the min (id) Judgment, half of the time is always the first few rows in the table.
The complete query statement is:
Select * from 'table'
Where id> = (select floor (rand () * (select max (id) from 'table')-(select min (id) from 'table ')) + (select min (id) from 'table ')))
Order by id limit 1;
Select *
From 'table' as t1 join (select round (rand () * (select max (id) from 'table')-(select min (id) from 'table ')) + (select min (id) from 'table') as id) as t2
Where t1.id> = t2.id
Order by t1.id limit 1;
Finally, in the php tutorial, query the two statements 10 times respectively,
The former takes 0.147433 seconds.
The latter takes 0.015130 seconds.

The above is how the mysql rand function implements random numbers.

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.