Lorenzo Tassone
Lorenzo Tassone

Reputation: 383

ORDER BY and LIMIT 2 different parameters


I have a table events which contains timestamp. I want to SELECTtwo events the next events coming out and the last 8 events in the past.
With two different queries it would be:
1)

SELECT * FROM events WHERE timestamp > timeNow ORDER BY timestamp LIMIT 0,2

2)

SELECT * FROM events WHERE timestamp < timeNow ORDER BY timestamp DESC LIMIT 0,8

Is it possible to do only one query?

Thanks

Upvotes: 0

Views: 285

Answers (1)

Tom Mac
Tom Mac

Reputation: 9853

Try a UNION or UNION ALL

SELECT * FROM events WHERE timestamp > timeNow ORDER BY timestamp LIMIT 2
UNION ALL
SELECT * FROM events WHERE timestamp < timeNow ORDER BY timestamp DESC LIMIT 8;

Also, remember LIMIT 8 is equivalent to LIMIT 0, 8. The reason for this is that LIMIT 0, 8 means "start at row 0 and restrict the number of rows returned to 8"

Upvotes: 1

Related Questions