栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Go语言

golang mysql动态sql查询条件及in条件查询写法

Go语言 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

golang mysql动态sql查询条件及in条件查询写法

golang mysql动态查询,条件拼接sql, in 查询
  • 需求: 多条件查询mysql数据内容;

需求: 多条件查询mysql数据内容;

条件: userId, keyword, starttime, endtime, loglevel(in 查询);
动态拼接sql使用如下: 原始sql拼接;
执行语句为

***err := m.conn.QueryRow( &count, sqlPageList + where, values...)***

mysql in查询的逻辑: 将in查询条件使用正则匹配"#“替换成” ?,? ", 然后占位符拼接参数Array 数组;
执行上面查询语句即可。

func (m *defaultVsmAuditLogModel) SelectCount(userId int64, req types.ReqAuditLog) (int, error) {
	var sqlPageList, where string
	var values []interface{}
	sqlPageList = "select count(1) " +
		"from vsm_audit_log  where 1=1 "
	if userId != 0 {
		where = where + " AND req_user = ?"
		values = append(values, userId)
	}
	if req.Keyword != "" {
		where = where + " AND operate_record like ?"
		values = append(values, "%" + req.Keyword + "%")
	}
	if req.StartTime != ""{
		where = where + " AND timestamp >= ?"
		st, _ := time.Parse("2006-01-02", req.StartTime)
		values = append(values, st)
	}
	if req.EndTime != ""{
		where = where + " AND timestamp < ?"
		et, _ := time.Parse("2006-01-02", req.EndTime)
		values = append(values, et)
	}
	var levelArr []int
	var count int
	if req.LogLevel!=nil && len(req.LogLevel)>0{
		//数组存在
		for _, levelStr := range req.LogLevel {
			var a int
			switch *levelStr{
			case "高级":
				a = 4
			case "中级":
				a = 3
			case "低级":
				a = 2
			case "信息级":
				a = 1
			case "无":
				a = 0
			}
			levelArr = append(levelArr, a)
		}
		where = where + " AND log_level in (#)"
		var dstr []string
		for l := 0; l < len(req.LogLevel); l++ {
			values = append(values, levelArr[l])
			dstr = append(dstr, "?")
		}
		regReplace:= strings.Join(dstr, ",")
		data := sqlPageList + where
		rep, _ := regexp.Compile("\#")
		sql := rep.ReplaceAllLiteralString(data, regReplace)

		err := m.conn.QueryRow( &count, sql, values...)
		switch err {
		case nil:
			return count, nil
		case sqlc.ErrNotFound:
			return 0, nil
		default:
			return 0, err
		}
	}else{
		err := m.conn.QueryRow( &count, sqlPageList + where, values...)
		switch err {
		case nil:
			return count, nil
		case sqlc.ErrNotFound:
			return 0, nil
		default:
			return 0, err
		}
	}
}

参考文档: https://github.com/suyaoli/example-001/blob/master/main.go

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/908274.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号