MySQL 如何按字段 DESC 排序,但首先列出 NULL 值
要按字段排序并首先列出 NULL 值,需要使用以下语法。这将按降序排列 –
select yourColumnName from yourTableName group by yourColumnName is null desc,yourColumnName desc;
为了理解上述语法,让我们首先创建一个表 –
mysql> create table OrderByNullFirstDemo
−> (
−> StudentId int
−> );
Query OK, 0 rows affected (0.56 sec)
使用 insert 命令在表中插入一些记录。查询如下 –
mysql> insert into OrderByNullFirstDemo values(100);
Query OK, 1 row affected (0.13 sec)
mysql> insert into OrderByNullFirstDemo values(200);
Query OK, 1 row affected (0.13 sec)
mysql> insert into OrderByNullFirstDemo values(150);
Query OK, 1 row affected (0.13 sec)
mysql> insert into OrderByNullFirstDemo values(NULL);
Query OK, 1 row affected (0.15 sec)
使用 select 语句显示表中的所有记录。显示所有记录的查询如下 –
mysql> select *from OrderByNullFirstDemo;
以下是输出 –
+-----------+
| StudentId |
+-----------+
| 100 |
| 200 |
| 150 |
| NULL |
+-----------+
4 行受影响 (0.00 sec)
实现我们在开头讨论的语法以按降序排序并显示 null 值 –
mysql> select StudentId from OrderByNullFirstDemo group by StudentId is null desc,StudentId desc;
下面是输出 –
+-----------+
| StudentId |
+-----------+
| NULL |
| 200 |
| 150 |
| 100 |
+-----------+
4 行受影响,2 行警告 (0.00 sec)
阅读更多:MySQL 教程
极客教程