开发者

How can I reverse the default ordering in MySQL?

开发者 https://www.devze.com 2022-12-12 11:13 出处:网络
In MySQL, when you execute a select SQL statement, there is a default ordering if you don\'t include a sorting clause. How can I reverse the d开发者_开发百科efault ordering? Just add DESC?You can set

In MySQL, when you execute a select SQL statement, there is a default ordering if you don't include a sorting clause. How can I reverse the d开发者_开发百科efault ordering? Just add DESC?


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.


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.


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


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"


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号