当前位置:网站首页>golang gorm查询任意字段的组装方法
golang gorm查询任意字段的组装方法
2022-07-28 02:58:00 【用户昵称不能为空】
查询指定未知长度字段的汇总方法
package main
import (
"fmt"
"github.com/jinzhu/gorm"
_ "github.com/jinzhu/gorm/dialects/mysql"
"log"
"strings"
)
type FilterDo struct {
}
type ScanFields interface {
IsScanField() bool
}
type Summary struct {
Num1 int `json:"num1"` // num1
Num2 int `json:"num2"` // num2
Num3 int `json:"num3"` // num3
Num4 int `json:"num4"` // num4
}
func (Summary) IsScanField() bool {
return true
}
var db *gorm.DB
func GetDB() *gorm.DB {
return db
}
type TableMember struct {
}
func ListCond(filter *FilterDo) (whereSql string, params []interface{
}) {
return
}
// SumFields gorm 实现指定查询任意字段
func SumFields(filter *FilterDo, results ScanFields, fields map[string]string) (err error) {
if len(fields) == 0 {
return
}
alias := make([]string, 0, len(fields))
names := make([]string, 0, len(fields)+1)
names = append(names, "m.id")
for k, v := range fields {
alias = append(alias, fmt.Sprintf("sum(%s) %s", strings.ReplaceAll(k, ",", "+"), v))
if v != "id" {
names = append(names, fmt.Sprintf("m.%s", strings.ReplaceAll(k, ",", ",m.")))
}
}
condition, params := ListCond(filter)
subQuery := GetDB().Model(&TableMember{
}).
Select("distinct "+strings.Join(names, ",")).
Table("table_member m").
Joins("left join a2 on m.user_id = a2.id ").
Joins("left join a3 on m.user_id = a3.user_id ").
Unscoped().
Where(condition, params...)
err = GetDB().Raw("select "+strings.Join(alias, ",")+" from ? a ", subQuery.SubQuery()).Scan(results).Error
return
}
func main() {
var (
err error
filter FilterDo
results Summary
)
fields := map[string]string{
"today_num": "num1",
"yes_num": "num2",
"last_num": "num3",
"today_num+last_num": "num4", // 组合
}
err = SumFields(&filter, results, fields)
if err != nil {
log.Fatal(err)
}
fmt.Println("results = ", results)
}
适用于使用汇总统计表的时候
边栏推荐
- How to reinstall win11 system with one click
- On weight decay and discarding method
- 对象数组转成strin再进行,隔开的字符串,包括赛选某个字段的子,或者求和,
- Redis内存回收
- [2022 Niuke Game 2 J question link with arithmetic progress] three part set three part / three part extreme value / linear equation fitting least square method
- IO analog serial port of stm32
- C -- switch case statement
- 20 soul chicken soup beautiful sentences, sentence by sentence warm heart!
- mysql存储过程 使用游标实现两张表数据同步数据
- 【2022 牛客第二场J题 Link with Arithmetic Progression】三分套三分/三分极值/线性方程拟合最小二乘法
猜你喜欢

汇总了50多场面试,4-6月面经笔记和详解(含核心考点及6家大厂)

如何解决mysql深分页问题

4、 Analysis of solid state disk storage technology (paper)

C WinForm development: how to add pictures to project resources

Redis 5 kinds of data structure analysis

光年(Light Year Admin)后台管理系统模板

一键重装win7系统详细教程

Uniapp - make phone calls and send text messages

Raspberry pie development relay control lamp

数据湖(十七):Flink与Iceberg整合DataStream API操作
随机推荐
[R language] environment specifies to delete RM function
redis网络模型解析
并发编程面试题总结
【AcWing 327. 玉米田】状压dp
What if the word selection box of win11 input method is missing?
“讳疾忌医”的开源走不远
ThreadLocal使用场景
Review basic knowledge points of engineering electromagnetic field
Shell:一键部署pxe
什么是虚函数?
Brush questions every day to consolidate knowledge
ThreadLocal usage scenario
What are the fragments of MySQL
When a dialog box pops up, the following form is not available
xctf攻防世界 Web高手进阶区 unserialize3
如何一键进行重装Win11系统
Four methods of closing forms in C #
Interview experience: first tier cities move bricks and face software testing posts. 5000 is enough
Redis implements distributed locks
My approval & signature function of conference OA project