Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

vertically stack MySQL results in single query

Tags:

mysql

How would I combine (stack vertically) the following 3 queries into one query that returns 100 rows, 50 rows from category 1, 25 from from category 2, 25 from category 3 all chosen randomly. 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;
like image 726
jeffery_the_wind Avatar asked Apr 02 '12 20:04

jeffery_the_wind


People also ask

How do I merge two MySQL queries?

The MySQL UNION operator is used to combine the result sets of 2 or more SELECT statements. It removes duplicate rows between the various SELECT statements. Each SELECT statement within the UNION operator must have the same number of fields in the result sets with similar data types.

How many queries can MySQL handle per second?

MySQL can run more than 50,000 simple queries per second on commodity server hardware and over 2,000 queries per second from a single correspondent on a Gigabit network, so running multiple queries isn't necessarily such a bad thing.

How do I show a string vertically in MySQL?

Vertical format is more readable where longer text lines are part of the output. To get this output format, start MySQL Shell with the --result-format=vertical command line option (or its alias --vertical ), or set the MySQL Shell configuration option resultFormat to vertical .


2 Answers

To apply ORDER BY or LIMIT to an individual SELECT, place the clause inside the parentheses that enclose the 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);
like image 134
Michael Fredrickson Avatar answered Sep 21 '22 23:09

Michael Fredrickson


What you are looking for is the UNION ALL syntax (link is 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

like image 40
scwagner Avatar answered Sep 17 '22 23:09

scwagner