开发者

MySQL limit from descending order

开发者 https://www.devze.com 2022-12-27 22:07 出处:网络
Is it available to write a query to use same \"LIMIT (from), (count)\", but get result in backwards? In example if I have 8 rows in the table and I want to get 5 rows in two steps I would:

Is it available to write a query to use same "LIMIT (from), (count)", but get result in backwards?

In example if I have 8 rows in the table and I want to get 5 rows in two steps I would: first step q开发者_JAVA百科uery:

select * from table limit 0, 5

first step result:

first 5 rows;

second step query:

select * from table limit 5, 5

second step result:

last 3 rows;

But I want to get it vice versa. I mean from the first step I want last 3 rows and from the second I want 5 first rows. Thank you for your answer


No, you shouldn't do this. Without an ORDER BY clause you shouldn't rely on the order of the results being the same from query to query. It might work nicely during testing but the order is indeterminate and could break later. Use an order by.

SELECT * FROM table1 ORDER BY id LIMIT 5

By the way, another way of getting the last 3 rows is to reverse the order and select the first three rows:

SELECT * FROM table1 ORDER BY id DESC LIMIT 3

This will always work even if the number of rows in the result set isn't always 8.


Let's say we have a table with a column time and you want the last 5 entries, but you want them returned to you in asc order, not desc, this is how you do it:

select * from ( select * from `table` order by `time` desc limit 5 ) t order by `time` asc


yes, you can swap these 2 queries

select * from table limit 5, 5

select * from table limit 0, 5


This way is comparatively more easy

SELECT doc_id,serial_number,status FROM date_time ORDER BY  date_time DESC LIMIT 0,1;
0

精彩评论

暂无评论...
验证码 换一张
取 消