https://www.lvtao.net/books/golang/go-nested-structure.html
第一:原生查询: Excel 除了查询,其他操作都可以
Go
// 联合查询(left join)
db.Table("go_service_info").Select("go_service_info.serviceId as service_id, go_service_info.serviceName as service_name, go_system_info.systemId as system_id, go_system_info.systemName as system_name").Joins("left join go_system_info on go_service_info.systemId = go_system_info.systemId").Scan(&results)
fmt.Println(mapToJson(results))
// where
db.Table("go_service_info").Select("go_service_info.serviceId as service_id, go_service_info.serviceName as service_name, go_system_info.systemId as system_id, go_system_info.systemName as system_name").Joins("left join go_system_info on go_service_info.systemId = go_system_info.systemId where go_service_info.serviceId <> ? and go_system_info.systemId = ?", "xxx", "xxx").Scan(&results)
fmt.Println(mapToJson(results))
// 原生sql
db.Raw("SELECT a.serviceId as service_id,a.serviceName as service_name, b.systemId as system_id, b.systemName as system_name FROM go_service_info a LEFT JOIN go_system_info b ON a.systemId = b.systemId").Scan(&results)
fmt.Println(mapToJson(results))
// where
db.Raw("SELECT a.serviceId as service_id,a.serviceName as service_name, b.systemId as system_id, b.systemName as system_name FROM go_service_info a LEFT JOIN go_system_info b ON a.systemId = b.systemId where a.serviceId <> ? and b.systemId = ?", "xxx", "xxx").Scan(&results)
fmt.Println(mapToJson(results))
原文链接:https://blog.csdn.net/baidu_37366055/article/details/128079638
sql 语句 可以取列表 和总数count
https://2048ai.net/681c1119e47cbf761b68f1cf.html
https://blog.csdn.net/daimading/article/details/85258007?login=from_csdn
用户是一对多的关系,即一个评论属于一个用户,一个用户可以发布多条评论
Go
func SelectSingleCommentByCondition(db *gorm.DB, where map[string]interface{}) (Comment, int64, error) {
var count int64 = 0
var comment Comment
err := db.Joins("Author").Where(where).First(&comment).Count(&count).Error
if count == 0 {
return comment, 0, errors.New("查询的记录不存在")
}
return comment, count, err
}
GORM 更新操作全解 ,子查询,gorm.Expr 执行数据库原生表达式,实现原子操作或复杂计算
Go
// 基于struct的批量更新
db.Model(&User{}).Where("role = ?", "admin").Updates(User{Name: "admin_user", Age: 40})
// 生成SQL: UPDATE users SET name='admin_user', age=40 WHERE role = 'admin';
// 基于map的批量更新
db.Table("users").Where("id IN ?", []int{10, 11, 12}).Updates(map[string]interface{}{"status": "inactive", "updated_at": time.Now()})
// 生成SQL: UPDATE users SET status='inactive', updated_at='...' WHERE id IN (10, 11, 12);
// 结合子查询的批量更新
db.Model(&Order{}).Where("amount < (?)", db.Table("orders").Select("AVG(amount)")).Updates(map[string]interface{}{"priority": 2})
// 生成SQL: UPDATE orders SET priority=2 WHERE amount < (SELECT AVG(amount) FROM orders);
作者:Code季风
链接:https://juejin.cn/post/7524864401616601114
来源:稀土掘金
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。