Home > Database > Mysql Tutorial > body text

How to Generate Random Numbers Between 1 and 3 in a MySQL Column?

Susan Sarandon
Release: 2024-10-26 07:19:30
Original
516 people have browsed it

How to Generate Random Numbers Between 1 and 3 in a MySQL Column?

Populating Column Values with Random Numbers

You seek to populate a database column with random numbers within a specified range for each record. Particularly, in your case, you desire to generate numbers between 1 and 3.

Solution:

To fulfill your request, consider utilizing the following MySQL query:

UPDATE tableName SET columnName = FLOOR( 1 + RAND( ) *3 );
Copy after login

Explanation:

The RAND() function in MySQL generates random floating-point values between 0 and 1. Multiplying this value by 3 and adding 1 ensures that the resulting number always falls within the range of 1 to 3.

Using the FLOOR() function then truncates the result to the nearest whole number, guaranteeing that you get integers within the specified range. This ensures that each record's columnName is replaced with a random number between 1 and 3.

The above is the detailed content of How to Generate Random Numbers Between 1 and 3 in a MySQL Column?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!