martes, 17 de junio de 2014

MySQL enteros aleatorios

Original post: http://anothermysqldba.blogspot.com/2014/06/mysql-random-integers.html

Esto no es una nueva característica, por cualquier medio, pero es una pregunta que me he suceder para ver estallar para arriba de vez en cuando. Así, un ejemplo rápido está siguiendo. 

Para generar un entero aleatorio dentro de MySQL puede utilizar el piso y las funciones de Rand. Los documentos manuales MySQL esta aquí: http://dev.mysql.com/doc/refman/5.5/en/mathematical-functions.html # function_rand 

" Para obtener un número entero aleatorio R en el intervalo i <= R <j, utilice el PISO expresión (i + RAND () * (j - i)) " 

Así que para dar un ejemplo: 

> SET @I = 3; # lower range 
> SET @J = 43 - @I; # max range minus lower range 

> SELECT FLOOR( @I + (RAND() * @J )) as lottery_numbers\G 
*************************** 1. row *************************** 
lottery_numbers: 4 
1 row in set (0.00 sec) 
> SELECT FLOOR( @I + (RAND() * @J )) as lottery_numbers\G 
*************************** 1. row *************************** 
lottery_numbers: 8 
1 row in set (0.00 sec 
> SELECT FLOOR( @I + (RAND() * @J )) as lottery_numbers\G 
*************************** 1. row *************************** 
lottery_numbers: 15 
1 row in set (0.00 sec 
> SELECT FLOOR( @I + (RAND() * @J )) as lottery_numbers\G 
*************************** 1. row *************************** 
lottery_numbers: 16 
1 row in set (0.00 sec 
> SELECT FLOOR( @I + (RAND() * @J )) as lottery_numbers\G 
*************************** 1. row *************************** 
lottery_numbers: 23 
1 row in set (0.00 sec 
> SELECT FLOOR( @I + (RAND() * @J )) as lottery_numbers\G 
*************************** 1. row *************************** 
lottery_numbers: 42 
1 row in set (0.00 sec