Mysql 使用 group by 不對 null 做分組


在項目開發查詢數據需要將相同的數據做合並處理,但是字段為null,不做合並。

創建表以及添加數據

create table t_student(
       `id` int not null primary key auto_increment,
       `name` varchar(32) ,
       `age` int   
)
insert into t_student(`name`,age) values("aa",11);
insert into t_student(`name`,age) values('bb',12);
insert into t_student(`name`,age) values('cc',13);
insert into t_student(`name`,age) values('cc',14);
insert into t_student(`name`,age) values('cc',15);
insert into t_student(`name`,age) values(null,16);
insert into t_student(`name`,age) values(null,17);

查詢數據一共有7條數據

select * from t_student

結果:

再做name合並

select * from t_student group by name

結果:

結果把全部null合並在一起了。

解決方案 使用替換UUID()

https://stackoverflow.com/questions/4588935/group-by-do-not-group-null上看到了一個方法。
做分組的時候如果name為null時,對null設置成一個隨機值UUID(),這樣就避免了null會合並的情況。
使用UUID():

select * from t_student group by IFNULL(name,UUID())

結果:


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM