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

发布于 2024-09-06 11:05:58 字数 223 浏览 8 评论 0原文

我想知道是否有一种简单的方法,只需一条sql语句即可返回表中的最后三个结果,但按该顺序,即如果有一百个结果,它将按 98, 99, 100 的顺序返回,而不是简单地排序id DESC 和 limit 3 将以 100, 99, 98 的顺序返回

非常感谢任何帮助。

ps 在这个例子中,假设我不知道结果的数量,并且真的不想发送 2 个 sql 请求只是为了找到数量(对于任何 OFFSET 答案)。

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 i.e. 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

Any help much appreciated.

p.s. 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 ).

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

—━☆沉默づ 2024-09-13 11:05:58

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

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

One way would be to use DESC and then just sort them again:

SELECT * FROM (SELECT * FROM some_table ORDER BY id DESC LIMIT 3) a ORDER BY id
卖梦商人 2024-09-13 11:05:58

我想有两个选择。

  1. 您可以使用 DESC 按照您所说的相反顺序返回它们,只需在应用程序代码中再次反转顺序即可。这可能是最有效的,因为您可以在单个查询中执行此操作,并且可能只需要读取索引的三行。

  2. 可以先查出表中的结果数,然后做LIMIT, 3

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. 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

叹沉浮 2024-09-13 11:05:58

只要把它翻回原来的顺序就可以了吗?

SELECT * FROM (SELECT * FROM SOMETABLE ORDER BY ID DESC LIMIT 3) AS T ORDER BY ID;

Is it okay if you just flip it back to the original order?

SELECT * FROM (SELECT * FROM SOMETABLE ORDER BY ID DESC LIMIT 3) AS T ORDER BY ID;
一片旧的回忆 2024-09-13 11:05:58
Select * 
FROM (SELECT * FROM yourTABLE ORDER BY ID DESC LIMIT 0,3) as TempTable ORDER BY ID
Select * 
FROM (SELECT * FROM yourTABLE ORDER BY ID DESC LIMIT 0,3) as TempTable ORDER BY ID
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文