MySQL Orderby a number, Nulls last(MySQL 按一个数字排序,最后为空)
问题描述
目前我正在做一个非常基本的 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 按一个数字排序,最后为空的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:MySQL 按一个数字排序,最后为空


基础教程推荐
- oracle区分大小写的原因? 2021-01-01
- 在 MySQL 中:如何将表名作为存储过程和/或函数参数传递? 2021-01-01
- 如何根据该 XML 中的值更新 SQL 中的 XML 2021-01-01
- 如何在 SQL 中将 Float 转换为 Varchar 2021-01-01
- mysql选择动态行值作为列名,另一列作为值 2021-01-01
- 什么是 orradiag_<user>文件夹? 2022-01-01
- 表 './mysql/proc' 被标记为崩溃,应该修复 2022-01-01
- 在多列上分布任意行 2021-01-01
- 二进制文件到 SQL 数据库 Apache Camel 2021-01-01
- MySQL 中的类型:BigInt(20) 与 Int(20) 2021-01-01