Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL: SELECT with UNION, ORDER BY and LIMIT

I'm getting Errors that ORDER by should come after UNION but i want these to queries ordered before combined to one and then limited to 10.

SELECT * 
  FROM (SELECT time, x, y, z 
          FROM db 
         WHERE time >= now 
      ORDER by time, x
       UNION 
       SELECT time, x, y, z 
         FROM db 
        WHERE time < now 
     ORDER by time, x) 
LIMIT 10

I hope you understand, what I'm trying to do and can help me ;-)

like image 688
Tobias Avatar asked Jan 14 '11 23:01

Tobias


People also ask

Can you use limit with UNION in SQL?

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.

Can we use ORDER BY in UNION query?

Union is a type of operator in MySQL. We can use ORDER BY with this to filter records. Use UNION if you want to select rows one after the other from several tables or several sets of rows from a single table all as a single result set. Let us see an example.

Does limit come before or after ORDER BY SQL?

So the key thing to notice is the specific order and arrangement of the SQL statement: just as FROM comes after the SELECT clause, LIMIT comes after both.

How do you use ORDER BY UNION?

As the following query shows, when you include an ORDER BY clause, it must follow the final SELECT statement and use an integer, not an identifier, to refer to the ordering column. Ordering takes place after the set operation is complete.


2 Answers

if you have a very complex query in SQLite but need to use UNION with ordering, then you can try

select * from (
    select * from b ORDER BY date asc
    )
UNION
select * from (
    select * from b ORDER BY name desc
    )
UNION
select * from (
    select * from b ORDER BY gender asc
    )
like image 158
hmaxf2 Avatar answered Oct 07 '22 17:10

hmaxf2


An order by will affect the ENTIRE union.

Anyway, it looks like you want the rows nearest to now. You could try this:

SELECT   time, x, y, z 
FROM     db 
ORDER BY ABS(time - now) ASC
LIMIT    10
like image 36
Andomar Avatar answered Oct 07 '22 17:10

Andomar