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 按一个数字排序,最后为空


基础教程推荐
- 在 VB.NET 中更新 SQL Server DateTime 列 2021-01-01
- Sql Server 字符串到日期的转换 2021-01-01
- ERROR 2006 (HY000): MySQL 服务器已经消失 2021-01-01
- SQL Server:只有 GROUP BY 中的最后一个条目 2021-01-01
- 如何在 SQL Server 的嵌套过程中处理事务? 2021-01-01
- SQL Server 2016更改对象所有者 2022-01-01
- 使用pyodbc“不安全"的Python多处理和数据库访问? 2022-01-01
- 无法在 ubuntu 中启动 mysql 服务器 2021-01-01
- SQL Server 中单行 MERGE/upsert 的语法 2021-01-01
- 将数据从 MS SQL 迁移到 PostgreSQL? 2022-01-01