2012-04-02 12 views
6

Come combinare (impilare verticalmente) le seguenti 3 query in una query che restituisce 100 righe, 50 righe dalla categoria 1, 25 dalla categoria 2, 25 dalla categoria 3 tutte scelte a caso. Ho provato UNION ma non sembra funzionare.stack verticale risultati MySQL in singola query

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

A 'UNION ALL' dovrebbe funzionare se si racchiude ciascuna parte in paren '(SELEZIONARE ...) UNIONE TUTTI (SELEZIONA ...) ...' –

risposta

6

Per applicare ORDER BY o LIMIT ad un individuo SELECT, posto clausola all'interno delle parentesi che racchiudono il 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

Quello che state cercando è la sintassi UNION ALL (link è alla documentazione 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; 

completa: virgola rimossa, grazie @ Matt Fenwick

+1

Tranne il punto e virgola. –

+0

quando tolgo il punto e virgola, ottengo solo 25 righe tutte da category_id = 1 –

Problemi correlati