Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MySQL - Using UNION with LIMIT

i noticed that

(SELECT title, relavency, 'search1' as source FROM search1
ORDER BY relavency DESC
LIMIT 10)
UNION 
(SELECT title, relavency, 'search2' as source FROM search2
ORDER BY relavency DESC
LIMIT 10)
ORDER BY relavency DESC 
LIMIT 10

the last LIMIT 10 does not work. why?

the error was

"Error code 1064: ... to use near 'LIMIT 1000'"

how come mysql workbench detects LIMIT 10 as LIMIT 1000, but if its 1000 it shld work still?

like image 1000
iceangel89 Avatar asked Sep 27 '09 02:09

iceangel89


People also ask

Can you use limit with UNION?

ORDER BY, LIMIT, and OFFSET Clauses in UNIONEach SELECT statement in a UNION clause can specify its own ORDER BY , LIMIT , and OFFSET clauses. In this case, the SELECT statement must be enclosed by parentheses.

Is there a limit to UNION in SQL?

You probably confused “union all” with “cross join”. There are no general limits on SQL statement length, but there can be restrictions in the specific DBMS.

How do I limit data in MySQL?

Assume we wish to select all records from 1 - 30 (inclusive) from a table called "Orders". The SQL query would then look like this: $sql = "SELECT * FROM Orders LIMIT 30"; When the SQL query above is run, it will return the first 30 records.


1 Answers

Your query can be rewritten using aliased nested subqueries. This should work for you:

SELECT u.* FROM (
    (SELECT s1.title, s1.relavency, 'search1' as source FROM search1 AS s1
    ORDER BY s1.relavency DESC
    LIMIT 10)
        UNION 
    (SELECT s2.title, s2.relavency, 'search2' as source FROM search2 AS s2
    ORDER BY s2.relavency DESC
    LIMIT 10)
) AS u ORDER BY u.relavency DESC 
LIMIT 10

FYI: you misspelled "relevancy" but I preserved the misspelling so the query would work.

like image 69
Asaph Avatar answered Oct 10 '22 03:10

Asaph