计算表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)
Pluck
将模型中的单个列作为地图查询,如果要查询多个列,可以使用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 uns