MySQL MySQL从降序限制

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2708992/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-31 15:53:21  来源:igfitidea点击:

MySQL limit from descending order

mysql

提问by faya

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

是否可以编写查询以使用相同的“LIMIT (from), (count)”,但向后得到结果?

In example if I have 8 rows in the table and I want to get 5 rows in two steps I would: first step query:

例如,如果我在表中有 8 行并且我想分两步获得 5 行,我会:第一步查询:

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 rowsand from the second I want 5 first rows. Thank you for your answer

但我想反之亦然。我的意思是从第一步开始我想要最后 3 行,从第二个开始我想要5 行。谢谢您的回答

回答by Mark Byers

No, you shouldn't do this. Without an ORDER BYclause 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.

不,你不应该这样做。如果没有ORDER BY子句,您不应该依赖于查询之间的结果顺序相同。它在测试期间可能会很好地工作,但顺序是不确定的,以后可能会中断。使用 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:

顺便说一句,另一种获取最后3行的方法是颠倒顺序并选择前三行:

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.

即使结果集中的行数并不总是 8,这也将始终有效。

回答by Dev Null

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:

假设我们有一个包含时间列的表,并且您想要最后 5 个条目,但是您希望它们以升序而不是降序返回给您,这是您的操作方式:

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

回答by Your Common Sense

yes, you can swap these 2 queries

是的,您可以交换这两个查询

select * from table limit 5, 5

select * from table limit 0, 5

回答by A.A Noman

This way is comparatively more easy

这种方式比较容易

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