BlogProgramming

MySQL: How to INSERT a random value

Problem: I have a large table with hundreds of test records, and would like to insert into a determined column a random user id, so the tests look more real in query results.

Solution: MySQL have a function RAND(), but it returns a random floating-point value v in the range 0 <= v < 1.0. Not what I want. The solution is to use it in conjunction with FLOOR(X), that will return the largest integer value not greater than X. So, to obtain a random integer R in the range i <= R < j, I can use the expression FLOOR(i + RAND() * (j – i)). For example, to obtain a random integer in the range the range 7 <= R < 12, I could use the following statement:

SELECT FLOOR(7 + (RAND() * 5));

And now, for my INSERT:

UPDATE `my_table` SET user_id = FLOOR(7 + RAND() * 5);

Did that worked out for you? Please let me know in the comments below.

Artigos Relacionados

Deixe um comentário

O seu endereço de email não será publicado. Campos obrigatórios marcados com *

Este site utiliza o Akismet para reduzir spam. Fica a saber como são processados os dados dos comentários.

Botão Voltar ao Topo
João Clérigo - Photography
Fechar

AdBlocker Detetado
AdBlocker Detected

Por favor ajude este website permitindo a visualização de alguns anúncios. Obrigado. Please help this website allowing the view of some advertising. Thank you!