MySQL ORDER BY ASC并在底部显示NULL?

为此,将CASE语句与ORDER BY一起使用。让我们首先创建一个表-

mysql> create table DemoTable1937
   (
   Name varchar(20)
   );

使用插入命令在表中插入一些记录-

mysql> insert into DemoTable1937 values('Chris');
mysql> insert into DemoTable1937 values(NULL);
mysql> insert into DemoTable1937 values('Adam');
mysql> insert into DemoTable1937 values('John');
mysql> insert into DemoTable1937 values('');
mysql> insert into DemoTable1937 values(NULL);
mysql> insert into DemoTable1937 values('Bob');

使用select语句显示表中的所有记录-

mysql> select * from DemoTable1937;

这将产生以下输出-

+-------+
| Name  |
+-------+
| Chris |
| NULL  |
| Adam  |
| John  |
|       |
| NULL  |
| Bob   |
+-------+
7 rows in set (0.00 sec)

这是对ORDER BY ASC的查询,并在底部显示NULL:

mysql> select * from DemoTable1937
   order by case when Name IS NULL then 100
   when Name='' then 101
   else 103
   end desc
   ,
   Name asc;

这将产生以下输出-

+-------+
| Name  |
+-------+
| Adam  |
| Bob   |
| Chris |
| John  |
|       |
| NULL  |
| NULL  |
+-------+
7 rows in set (0.00 sec)