MySQL vertical stack leads to a single query

How to combine (stack vertically) the following 3 queries into one query , which returns 100 rows, 50 rows from category 1, 25 from category 2, 25 from category 3, all are randomly selected. I tried UNION but didn't seem to work.

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; 
+6
source share
2 answers

To apply ORDER BY or LIMIT to an individual SELECT , place the SELECT in parentheses that enclose 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); 
+6
source

What you are looking for is UNION ALL syntax (link to MySQL documentation).

 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; 

edit: semicolons removed, thanks @Matt Fenwick

+3
source

Source: https://habr.com/ru/post/912257/


All Articles