简体   繁体   English

MySQL-返回表中的最后3个结果

[英]Mysql - return last 3 results in table

i was wondering if there was an easy way with just an sql statement to return the last three results in the table but in that order ie if there are a hundered results it would return in the order of 98, 99, 100 not simply ordering by id DESC and limit 3 which would return in order 100, 99, 98 我想知道是否有一种简单的方法仅用一条sql语句返回表中的最后三个结果,但是按该顺序,即如果有盘旋的结果,它将以98、99、100的顺序返回,而不是简单地按ID DESC和限制3(按顺序返回100、99、98)

Any help much appreciated. 任何帮助,不胜感激。

ps in this instance, lets say I don't know the amount of results and don't really want to send 2 sql requests just to find the amount ( for any OFFSET answers ). ps在这种情况下,可以说我不知道​​结果的数量,也不想真正发送2个sql请求只是为了找到数量(对于任何OFFSET答案)。

一种方法是使用DESC ,然后再次对其进行排序:

SELECT * FROM (SELECT * FROM some_table ORDER BY id DESC LIMIT 3) a ORDER BY id

Two options, I guess. 我猜有两个选择。

  1. You could use DESC to return them in reverse order as you stated, and just reverse the order again in your application code. 您可以使用DESC按照相反的顺序返回它们,而只需在应用程序代码中再次颠倒该顺序即可。 This is potentially the most efficient, as you can do it in a single query and it can potentially only need to read three rows of an index. 这可能是最有效的,因为您可以在单个查询中完成操作,并且可能只需要读取索引的三行即可。

  2. You can first find out the number of results in the table, then do a LIMIT <results-3> , 3 您可以先在表中找出结果数,然后执行LIMIT <results-3> ,3

只需将其翻转回原始顺序就可以了吗?

SELECT * FROM (SELECT * FROM SOMETABLE ORDER BY ID DESC LIMIT 3) AS T ORDER BY ID;
Select * 
FROM (SELECT * FROM yourTABLE ORDER BY ID DESC LIMIT 0,3) as TempTable ORDER BY ID

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM