How to reverse the default ordering in Mysql?

旧时模样 提交于 2019-11-28 07:36:48

问题


In Mysql, when you execute a select SQL statement, there is a default ordering if you don't include a sorting clause, how to reverse the default ordering? Just add DESC?


回答1:


If you want the data to come out consistently ordered, you have to use ORDER BY followed by the column(s) you want to order the query by. ASC is the default, so you don't need to specify it. IE:

ORDER BY your_column

...is the equivalent to:

ORDER BY your_column ASC

ASC/DESC is on a per column basis. For example:

ORDER BY first_column, second_column DESC

...means that the query will sort the resultset as a combination using the first_column in ascending order, second_column in descending order.




回答2:


There is no guaranteed order if you don't specify an ORDER BY clause, thus the 'reverse of the default order' is undefined.




回答3:


You can set a counter in your result fields and sort using it:

SELECT *, @counter := @counter + 1 AS 'counter' FROM tableName, (SELECT @counter := 0) r ORDER BY counter DESC

I think it will work as you want.




回答4:


I think you would be better served by specifying the order you actually want. Tables, by their nature, have no order. It is probably just displayed in the order in which the rows were inserted - though there's no guarantee it will stay in that order.

Chances are, you probably just want to add this:

ORDER BY id DESC

...since most of the time, people use an auto-incrementing field called "id"




回答5:


Unless you can specify a column name in an ORDER BY clause, you can't use DESC, and you'll have to resort to tricks involving LIMIT to see the last few records.

This would be unsatisfactory, I think.



来源:https://stackoverflow.com/questions/1807079/how-to-reverse-the-default-ordering-in-mysql

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