如何按字段排序DESC,但首先列出NULL值?
要按字段排序并首先列出NULL值,您需要使用以下语法。这将以降序排列-
select yourColumnName from yourTableName group by yourColumnName is null desc,yourColumnName desc;
要了解上述语法,让我们首先创建一个表-
mysql> create table OrderByNullFirstDemo −> ( −> StudentId int −> );
借助insert命令将一些记录插入表中。查询如下-
mysql> insert into OrderByNullFirstDemo values(100); mysql> insert into OrderByNullFirstDemo values(200); mysql> insert into OrderByNullFirstDemo values(150); mysql> insert into OrderByNullFirstDemo values(NULL);
在select语句的帮助下显示表中的所有记录。显示所有记录的查询如下-
mysql> select *from OrderByNullFirstDemo;
以下是输出-
+-----------+ | StudentId | +-----------+ | 100 | | 200 | | 150 | | NULL | +-----------+ 4 rows in set (0.00 sec)
实现我们在开始时讨论的语法,以降序执行顺序并显示空值efirst-
mysql> select StudentId from OrderByNullFirstDemo group by StudentId is null desc,StudentId desc;
以下是输出-
+-----------+ | StudentId | +-----------+ | NULL | | 200 | | 150 | | 100 | +-----------+ 4 rows in set, 2 warnings (0.00 sec)