Gorm中使用sum查询没有数据返回null的一个问题
sum函数没有查到数据默认返回NULL,需要用IFNULL函数判断下
package gorm_tests import ( "fmt" "github.com/stretchr/testify/require" "gorm.io/driver/mysql" "gorm.io/gorm" "testing" "time" ) /* CREATE TABLE `lottery` ( `id` int(10) unsigned NOT NULL AUTO_INCREMENT, `activity_id` int(10) unsigned NOT NULL, `total_limit` int(10) unsigned NOT NULL, `daily_limit` int(10) unsigned NOT NULL, `create_at` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP, `update_at` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, PRIMARY KEY (`id`), UNIQUE KEY `idx_activity_id` (`activity_id`) USING BTREE ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4; */ const ( LotteryTableName = "lottery" ) type Lottery struct { Id uint32 `gorm:"column:id" json:"id"` ActivityId uint32 `gorm:"column:activity_id" json:"activityId"` // 活动id,唯一索引 TotalLimit uint32 `gorm:"column:total_limit" json:"totalLimit"` // 总次数限制 DailyLimit uint32 `gorm:"column:daily_limit" json:"dailyLimit"` // 每日次数限制 CreateAt time.Time `gorm:"column:create_at;default:null" json:"createAt"` // 创建时间 UpdateAt time.Time `gorm:"column:update_at;default:null" json:"updateAt"` // 更新时间 } func (l *Lottery) TableName() string { return LotteryTableName } func TestT4(t *testing.T) { dsn := "root:123@tcp(127.0.0.1:3306)/test?charset=utf8mb4&parseTime=True&loc=Local" db, err := gorm.Open(mysql.Open(dsn), &gorm.Config{}) require.Equal(t, err, nil) fmt.Println("db: ", db) var sum int64 var count int64 // Notice 如果数据库中没有数据,count默认返回0 errCount := db.Table(LotteryTableName).Select("count(total_limit) as count").Find(&count).Error require.Equal(t, errCount, nil) fmt.Println("count: ", count) // 0 // 会报错!!!!!! // Notice 如果数据库中没有查到数据,sum默认返回null,此时用int64数据解析会报错! //errSum := db.Table(LotteryTableName).Select("sum(total_limit) as sum").Find(&sum).Error //require.Equal(t, errSum, nil) //fmt.Println("sum: ", sum) // Notice 正确使用sum的方法 IFNULL函数判断 errSum := db.Table(LotteryTableName).Select("IFNULL(sum(total_limit), 0) as sum").Find(&sum).Error require.Equal(t, errSum, nil) fmt.Println("sum: ", sum) // 0 }
~~~