Go GORM关联查询学生违规记录数与总扣分值始终返回0求助
问题原因
- 核心问题:
ViolationSummary结构体的count和sum字段首字母为小写,属于Go语言的未导出私有字段,GORM的Scan方法无法通过反射给私有字段赋值,因此两个字段一直保持int类型的默认值0。 - 可选优化点:当指定学生没有违规记录时,SQL的
sum()聚合函数会返回NULL,直接映射到int类型也会得到0,无法区分「真的没有违规总分为0」和「查询异常返回0」的情况。
修复方案
步骤1:修改统计结果结构体,将字段改为导出(首字母大写),可搭配gorm标签明确映射字段别名
type ViolationSummary struct { Count int `gorm:"column:count"` Sum int `gorm:"column:sum"` }
步骤2:优化SQL查询,对sum结果做IFNULL处理,避免NULL值问题
func(s *Server) ShowSummary(id int){ var vs ViolationSummary s.DB.Table("violation_records"). Select("count(violation_records.id) as count, IFNULL(sum(violations.violation_point), 0) as sum"). Joins("left join violations on violation_records.violation_id=violations.id"). Where("student_id = ?", id). Scan(&vs) fmt.Println(vs.Count) fmt.Println(vs.Sum) }
内容的提问来源于stack exchange,提问作者user10141827
相关产品推荐
相关产品推荐

