MySQL 查询两个字段和 NULL 值按时间顺序排列
让我们首先创建一个表-
mysql> create table DemoTable -> ( -> FirstName varchar(100), -> LastName varchar(100) -> ); Query OK, 0 rows affected (1.39 sec)
使用插入命令在表中插入一些记录-
mysql> insert into DemoTable values('Sam','Brown'); Query OK, 1 row affected (0.25 sec) mysql> insert into DemoTable values(null,'Smith'); Query OK, 1 row affected (0.16 sec) mysql> insert into DemoTable values('David','Taylor'); Query OK, 1 row affected (0.22 sec) mysql> insert into DemoTable values('Mike',null); Query OK, 1 row affected (0.45 sec)
使用select语句显示表中的所有记录-
mysql> select *from DemoTable;
输出结果
这将产生以下输出-
+-----------+----------+ | FirstName | LastName | +-----------+----------+ | Sam | Brown | | NULL | Smith | | David | Taylor | | Mike | NULL | +-----------+----------+ 4 rows in set (0.06 sec)
这是按两个字段排序的查询,按时间顺序可能为NULL值-
mysql> select *from DemoTable order by coalesce(FirstName,LastName);
输出结果
这将产生以下输出-
+-----------+----------+ | FirstName | LastName | +-----------+----------+ | David | Taylor | | Mike | NULL | | Sam | Brown | | NULL | Smith | +-----------+----------+ 4 rows in set (0.04 sec)