Devuelve filas en orden aleatorio [duplicar]
Esta pregunta ya tiene una respuesta aquí:
- ¿Cómo seleccionar filas al azar en SQL? 9 respuestas
¿Es posible escribir una consulta SQL que devuelve filas de tabla en orden aleatorio cada vez que se ejecuta la consulta?
6 answers
SELECT * FROM table
ORDER BY NEWID()
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.
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();
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.
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);
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
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