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;
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.
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.
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 .
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);
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With