项目用的是hibernate, 要求dao中不能使用原生的sql, 要用hql, 不熟, 遇到了很多问题
1. 去重统计问题
需求: 查出某张表中某个字段的个数, 需要去重.
hql :select count(DISTINCT s.teacher.id) from student as s
注意: distinct 去重, 与字段之间不能有 ( , 否则会报错
2. 将 null 值转为 0
需求: 做统计时, 如果没有数据, 正常的sum将返回 null , 但是需要返回 0 , 此时可以用 coalesce() 函数
hql : select sum(s.score) from student s // 此时, 如果没查到数据, 返回 null 值
select coalesce(s.score, 0) from student s; // 经过此函数, 将返回 0
coalesce() 函数返回的是第一个非 null 值, 例如 : coalesce(null, null ,1, 8, null) 将返回 1,