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 ;-)
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.
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.
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.
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.
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 )
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
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