2012-04-02 15 views
6

¿Cómo combinaría (apilará verticalmente) las siguientes 3 consultas en una consulta que devuelve 100 filas, 50 filas de la categoría 1, 25 de la categoría 2, 25 de la categoría 3 todas elegidas al azar. Intenté UNION pero no parecía funcionar.apila verticalmente los resultados de MySQL en una sola consulta

select * from table where category_id = 1 order by rand() limit 50; 

select * from table where category_id = 2 order by rand() limit 25; 

select * from table where category_id = 3 order by rand() limit 25; 
+3

Un 'UNION ALL' debería funcionar si encierra cada parte en parens '(SELECT ...) UNION ALL (SELECT ...) ...' –

Respuesta

6

Para aplicar ORDER BY o LIMIT a un individuo SELECT, colocar la cláusula dentro de los paréntesis que encierran el SELECT:

(select * from table where category_id = 1 order by rand() limit 50) 
UNION ALL 
(select * from table where category_id = 2 order by rand() limit 25) 
UNION ALL 
(select * from table where category_id = 3 order by rand() limit 25); 
3

Lo que se busca es la sintaxis UNION ALL (enlace es a la documentación de MySQL).

select * from table where category_id = 1 order by rand() limit 50 
UNION ALL 
select * from table where category_id = 2 order by rand() limit 25 
UNION ALL 
select * from table where category_id = 3 order by rand() limit 25; 

de edición: Punto y coma eliminado, gracias @ Matt Fenwick

+1

Excepto por los puntos y comas. –

+0

cuando saco los puntos y comas, acabo de obtener 25 filas todas de category_id = 1 –

Cuestiones relacionadas