如何防止 MySQL GROUP BY 将 NULL 值折叠到单行中?


要实现这一目标,可将 IFNULL() 与 ORDER BY 子句结合使用。我们先创建一个名为表 table 的表 -

mysql> create table DemoTable1511
   -> (
   -> Id int NOT NULL AUTO_INCREMENT PRIMARY KEY,
   -> FirstName varchar(20)
   -> );
Query OK, 0 rows affected (1.97 sec)

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

mysql> insert into DemoTable1511(FirstName) values('John');
Query OK, 1 row affected (0.20 sec)
mysql> insert into DemoTable1511(FirstName) values('Robert');
Query OK, 1 row affected (0.29 sec)
mysql> insert into DemoTable1511(FirstName) values('Mike');
Query OK, 1 row affected (0.10 sec)
mysql> insert into DemoTable1511(FirstName) values('Robert');
Query OK, 1 row affected (1.08 sec)
mysql> insert into DemoTable1511(FirstName) values(NULL);
Query OK, 1 row affected (0.68 sec)
mysql> insert into DemoTable1511(FirstName) values(NULL);
Query OK, 1 row affected (1.91 sec)
mysql> insert into DemoTable1511(FirstName) values('Mike');
Query OK, 1 row affected (0.51 sec)

使用 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)

更新日期:2019-12-11

947 次查看

开启你的职业生涯

完成本课程并获得认证

开始
广告