Devuelve filas en orden aleatorio [duplicar]


Esta pregunta ya tiene una respuesta aquí:

¿Es posible escribir una consulta SQL que devuelve filas de tabla en orden aleatorio cada vez que se ejecuta la consulta?

Author: trejder, 2009-07-13

6 answers

SELECT * FROM table
ORDER BY NEWID()
 163
Author: Dave Barker,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-09-21 08:38:28

Esta es la solución más simple:

SELECT quote FROM quotes ORDER BY RAND() 

Aunque no es el más eficiente. Este es una mejor solución.

 20
Author: Alec Smart,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-06-23 07:07:01

El método habitual es usar la función NEWID (), que genera un GUID único. Entonces,

SELECT * FROM dbo.Foo ORDER BY NEWID();
 12
Author: devstuff,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2009-07-13 05:09:10

Para ser eficiente y aleatorio, podría ser mejor tener dos consultas diferentes.

Algo así...

SELECCIONE table_id DE la tabla

Luego, en el idioma elegido, elija un id aleatorio y luego tire de los datos de esa fila.

SELECCIONE * DE la tabla DONDE table_id =rand rand_id

Pero eso no es realmente una buena idea si esperas tener muchas filas en la tabla. Sería mejor si pones algún tipo de límite en lo que seleccionas al azar. Para publicaciones, tal vez elegir al azar de solo los elementos publicados en el último año.

 0
Author: nilamo,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2009-07-13 15:24:20

Aquí hay un ejemplo (fuente):

SET @randomId = Cast(((@maxValue + 1) - @minValue) * Rand() + @minValue AS tinyint);
 0
Author: PinoyDev,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-06-23 07:07:36

Esto es lo que necesitas:

SELECT * FROM table_name ORDER BY RAND () LIMIT 1

 -1
Author: Dan Both,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-04-07 22:12:28