MySQL ORDER BY ASC 并在底部显示 NULL?
mysqlmysqli database
为此,请使用带有 ORDER BY 的 CASE 语句。让我们首先创建一个表 −
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)
这是按 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)