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 PL/SQL developer 生成测试数据 2021-01-01
- 更改自动增量起始编号? 2021-01-01
- SQL 临时表问题 2022-01-01
- 远程 mySQL 连接抛出“无法使用旧的不安全身份验证连接到 MySQL 4.1+"来自 XAMPP 的错误 2022-01-01
- 导入具有可变标题的 Excel 文件 2021-01-01
- 如何将 SonarQube 6.7 从 MySQL 迁移到 postgresql 2022-01-01
- 如何将 Byte[] 插入 SQL Server VARBINARY 列 2021-01-01
- 在SQL中,如何为每个组选择前2行 2021-01-01
- 如何使用 pip 安装 Python MySQLdb 模块? 2021-01-01
- 以一个值为轴心,但将一行上的数据按另一行分组? 2022-01-01