为此,您可以将其IFNULL()
与ORDER BY子句一起使用。让我们首先创建一个表table-
mysql> create table DemoTable1511 -> ( -> Id int NOT NULL AUTO_INCREMENT PRIMARY KEY, -> FirstName varchar(20) -> );
使用插入命令在表中插入一些记录-
mysql> insert into DemoTable1511(FirstName) values('John'); mysql> insert into DemoTable1511(FirstName) values('Robert'); mysql> insert into DemoTable1511(FirstName) values('Mike'); mysql> insert into DemoTable1511(FirstName) values('Robert'); mysql> insert into DemoTable1511(FirstName) values(NULL); mysql> insert into DemoTable1511(FirstName) values(NULL); mysql> insert into DemoTable1511(FirstName) values('Mike');
使用select语句显示表中的所有记录-
mysql> select * from DemoTable1511;
这将产生以下输出-
+----+-----------+ | Id | FirstName | +----+-----------+ | 1 | John | | 2 | Robert | | 3 | Mike | | 4 | Robert | | 5 | NULL | | 6 | NULL | | 7 | Mike | +----+-----------+ 7 rows in set (0.00 sec)
这是防止MySQL GROUP BY将NULL值折叠为单行的查询-
mysql> select min(Id) as Id,FirstName from DemoTable1511 group by FirstName,ifnull(FirstName,Id) order by Id;
这将产生以下输出-
+------+-----------+ | Id | FirstName | +------+-----------+ | 1 | John | | 2 | Robert | | 3 | Mike | | 5 | NULL | | 6 | NULL | +------+-----------+ 5 rows in set (0.00 sec)