目前我正在做一个非常基本的 OrderBy 语句.
Currently I am doing a very basic OrderBy in my statement.
SELECT * FROM tablename WHERE visible=1 ORDER BY position ASC, id DESC
这里的问题是位置"的 NULL 条目被视为 0.因此,所有位置为 NULL 的条目都出现在 1、2、3、4 的条目之前.例如:
The problem with this is that NULL entries for 'position' are treated as 0. Therefore all entries with position as NULL appear before those with 1,2,3,4. eg:
NULL, NULL, NULL, 1, 2, 3, 4
有没有办法实现以下排序:
Is there a way to achieve the following ordering:
1, 2, 3, 4, NULL, NULL, NULL.
MySQL 有一个未公开的语法来最后对空值进行排序.在列名前放置一个减号 (-) 并将 ASC 切换为 DESC:
MySQL has an undocumented syntax to sort nulls last. Place a minus sign (-) before the column name and switch the ASC to DESC:
SELECT * FROM tablename WHERE visible=1 ORDER BY -position DESC, id DESC
它本质上是 position DESC
的逆,将 NULL 值放在最后,但其他方面与 position ASC
相同.
It is essentially the inverse of position DESC
placing the NULL values last but otherwise the same as position ASC
.
这里有一个很好的参考http://troels.arvin.dk/db/rdbms#select-order_by
这篇关于MySQL 按一个数字排序,最后为空的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持html5模板网!