MySQL ORDER BY ASC 并显示 NULL 值到底部?
为此,将 CASE 语句与 ORDER BY 结合使用。让我们首先创建一个表 -
mysql> create table DemoTable1937 ( Name varchar(20) ); Query OK, 0 rows affected (0.00 sec)
使用 insert 命令在表中插入一些记录 -
mysql> insert into DemoTable1937 values('Chris'); Query OK, 1 row affected (0.00 sec) mysql> insert into DemoTable1937 values(NULL); Query OK, 1 row affected (0.00 sec) mysql> insert into DemoTable1937 values('Adam'); Query OK, 1 row affected (0.00 sec) mysql> insert into DemoTable1937 values('John'); Query OK, 1 row affected (0.00 sec) mysql> insert into DemoTable1937 values(''); Query OK, 1 row affected (0.00 sec) mysql> insert into DemoTable1937 values(NULL); Query OK, 1 row affected (0.00 sec) mysql> insert into DemoTable1937 values('Bob'); Query OK, 1 row affected (0.00 sec)
使用 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)
广告