时间:2022-01-04 10:56:35 | 栏目:Golang | 点击:次
计算表lb_ytt_user_money_log 中,字段money的和
代码如下:
var total_money []int sqlstr := `select SUM(money) as total_money from lb_ytt_user_money_log where user_id = ? and l_type = 1 and status=1 and (create_time> ? and create_time <= ?)` Db.Raw(sqlstr, userID, beginTimeNum, endTimeNum).Pluck("SUM(money) as total_money", &total_money)
将模型中的单个列作为地图查询,如果要查询多个列,可以使用Scan
Db.Raw(sqlstr, userID, beginTimeNum, endTimeNum).Pluck("SUM(money) as total_money", &total_money)
如果把Db.Pluck换成Db.scan得出的就是0
补充:golang gorm 解决mysql sum函数列有null时 报错 sconverting NULL to int64 is unsupported
当我们查询orders表order_amount字段的和时,如果order_amount字段有null值,则gorm会报错sql:
Scan error on column index 0, name "sum(order_amount)": converting NULL to int64 is unsupported
var price int64
db.Table("orders").Select("sum(order_amount)").Scan(&price)
使用gorm的Pluck 从数据库查询单个列,并将结果扫描到切片,在循环取出值计算总和,这样即使有null值,也能正确计算和,不会因为sum函数的机制导致报错
//创建一个存储查询结果的切片 var result []int64 var sum int64 db.Table("orders").Pluck("order_amount",&result ) for _,v := range result{ sum += v }