Combining UNION and LIMIT operations in MySQL query
89,677
Solution 1
Quoting the docs,
To apply ORDER BY or LIMIT to an individual SELECT, place the clause inside the parentheses that enclose the SELECT:
(SELECT a FROM t1 WHERE a=10 AND B=1 ORDER BY a LIMIT 10)
UNION
(SELECT a FROM t2 WHERE a=11 AND B=2 ORDER BY a LIMIT 10);
Solution 2
Improving on Alex's answer and based on Joe's observation, the following should work in SQLite:
SELECT * FROM
(SELECT a FROM t1 WHERE a=10 AND B=1 ORDER BY a LIMIT 10)
UNION
(SELECT a FROM t2 WHERE a=11 AND B=2 ORDER BY a LIMIT 10);
![Admin](/assets/logo_square_200-5d0d61d6853298bd2a4fe063103715b4daf2819fc21225efa21dfb93e61952ea.png)
Author by
Admin
Updated on July 08, 2022Comments
-
Admin almost 2 years
I have a Jobs and a Companies table, and I want to extract 20 jobs that meet the following criteria:
- Jobs only from two (2) named companies
- There can at most be 10 jobs per company
I have tried the following
SELECT
withUNION DISTINCT
, but the problem is that theLIMIT 0,10
applies to the whole result set. I want it to apply to each of the companies.If there aren't 10 jobs per company, then the query should return all the jobs it finds.
SELECT c.name, j.title, j.`desc`, j.link FROM jobs_job j INNER JOIN companies_company c ON j.company_id = c.id WHERE c.name IN ('Company1') UNION DISTINCT SELECT c.name, j.title, j.`desc`, j.link FROM jobs_job j INNER JOIN companies_company c ON j.company_id = c.id WHERE c.name IN ('Company2') ORDER by name, title LIMIT 0,10
I am new to MySQL, so realise there may be a smarter way to do this instead of with UNION, so any suggestions for improvements are definitely welcome.
-
Admin almost 15 yearsI was going by the MySQL documentation that said the ORDER BY came after the UNION.....and forgot about the parentheses! Thanks
-
Alex Martelli almost 15 years@Mauro, che ne dici di accettare la risposta, se ti risolve il problema, eh?!-) Usa il segno di "checkmark" sotto il numero di upvotes (attualmente tre...)...
-
Joe Lyga almost 12 yearsThis works in MySql, but it doesn't look like SQLite supports this in case anyone runs into this question on google
-
hugo24 about 10 yearsIt will return max 20 records. And only if those are unique rows. U have to use UNION ALL on non-unique rows.
-
Pj Toopmuch over 3 yearsanswer needed a slight modification for me on SQLite.
sql SELECT * FROM (SELECT a FROM t1 WHERE a=10 AND B=1 ORDER BY a LIMIT 10) UNION SELECT * FROM (SELECT a FROM t2 WHERE a=11 AND B=2 ORDER BY a LIMIT 10);
-
carnini about 3 yearsPrefect, just what I needed to get the fields I needed with limits on my two queries
-
Arpan Saini about 3 yearswe can use either "" or instead of "" you can use , "user_defined_name1.*". Both approach works