Mysql 使用 group by 不對 null 做分組
阿新 • • 發佈:2021-10-21
在專案開發查詢資料需要將相同的資料做合併處理,但是欄位為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())
結果: