SQL: SELECT with UNION, ORDER BY and LIMIT

I get Errors that ORDER should appear after UNION, but I want these requests to be ordered before merging, 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 ,-)

+5
source share
5 answers

This is not how it works, at least in MySQL (you did not specify). The ORDER operation is performed after selecting data and executing all UNION, GROUP BY, etc.

See SQL Server: ORDER BY in a subquery with UNION to get around this.

+4
source

SQLite, UNION ,

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
    )
+21

ENTIRE.

, , , now. :

SELECT   time, x, y, z 
FROM     db 
ORDER BY ABS(time - now) ASC
LIMIT    10
+7

"" ( "" ) SQL;

select top 10 *
from (       select time,x,y,z from db where time > now
       union select time,x,y,z from db where time < now
     ) t
order by t.time

, SQL.

+4

, , :

SELECT 
 name,
 TO_DATE(date1, 'DD-MON-YYYY HH:MI AM')
FROM TableX

UNION

SELECT
 name,
 TO_DATE(date2, 'DD-MON-YYYY HH:MI AM')
FROM TableY

ORDER BY 2 DESC;

().

If the date column is a row, you can use the TO_DATE function as shown above, otherwise it is not needed.

+2
source

All Articles