Mysql - 返回表中的最后 3 个结果
我想知道是否有一种简单的方法,只需一条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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
一种方法是使用
DESC
然后再次对它们进行排序:One way would be to use
DESC
and then just sort them again:我想有两个选择。
您可以使用 DESC 按照您所说的相反顺序返回它们,只需在应用程序代码中再次反转顺序即可。这可能是最有效的,因为您可以在单个查询中执行此操作,并且可能只需要读取索引的三行。
可以先查出表中的结果数,然后做LIMIT , 3
Two options, I guess.
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.
You can first find out the number of results in the table, then do a LIMIT <results-3>, 3
只要把它翻回原来的顺序就可以了吗?
Is it okay if you just flip it back to the original order?