1

Assuming I have a MySQL Table which contains two columns and I perform (it could not be simpler) a query

select * from test order by prio asc, datum asc

which gives me as expected this result:

datum      | prio
2017-07-02 | 1 
2017-07-09 | 2
2017-06-11 | 3
2017-06-01 | 4
2017-06-18 | 5
2017-06-25 | 6

Now, I want to limit my result to have ONLY the last 3 rows, with avoid doing something with an offset, because then I have to count the rows, so I know that this works:

select * from test order by prio asc, datum asc limit 3,3

But is there a trick, that I can do something similar to:

select * from test order by prio asc, datum asc limit -3  

I know this fails.

Thank you

Allan Karlson
  • 453
  • 11
  • 23

1 Answers1

5

Try below query.

SELECT * FROM(
    SELECT * FROM test ORDER BY prio DESC LIMIT 0,3
) t ORDER BY prio ASC, datum asc;

Subquery will sort descending based on priority and return last 3 records. Outer query will again sort those priorities in ascending order and then sort on datum.

Hope this will help you.

Mit Mehta
  • 212
  • 1
  • 8