Reverse the “natural order” of a MySQL table without ORDER BY?

我的梦境 提交于 2019-12-01 11:18:01

Use @rownum in your query to number each row and then order by the @rownum desc. Here's an example.

select @rownum:=@rownum+1 ‘rank’, p.* from player p, (SELECT @rownum:=0) r order by score desc limit 10;

Finally, beware that relying on the current order being returned long-term isn't recommended.

If you're writing an application to process the data, another approach might be to run your current query, then iterate over the returned records from last to first.

If you have too many records, then you may wish to instead use a view. This is a Database object which can be used to combine data from different tabls, or present a modified view of a single table, amongst other things. In this case, you could try creating a view of your table and add a generated ID column. You could then run SELECT statements against this view ordering by the new column you have added.

However be aware of the advice from another poster above: the order in which rows are returned without an ORDER BY clause is arbitrary and may change without notification. It would be best to amend your table if at all possible.

mySQL CREATE VIEW syntax

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!